Sunday, February 22, 2015

Pointers in c

What is a Pointer?

A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type.

The unary or monadic operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.
To declare a pointer to a variable do:
   int *pointer;
 
1st example: x value is 1 and address is 100 
in ip we assign the address of x into ip.

2nd example: *ip means getting the value at the address
contained by ip . so ip has 100 and at that address it has value 1 
so that value is assigned to y.

3rd example: we assign the value of ip that is 100 to x so x now has 100.

4th example: now this is tricky so try to understand this carefully.
*ip means assigning the value at the address contained by ip (100)
so at the address assign value 3 .
now the memory address 100 the value is 3.
as x's address is 100 so now x value also is now 3. 


We can do integer arithmetic on a pointer:


   float *flp, *flq;
 
   *flp = *flp + 10;
 
   ++*flp;
 
   (*flp)++;
 
   flq = flp;
NOTE: A pointer to any variable type is an address in memory -- which is an integer address. A pointer is definitely NOT an integer.
The reason we associate a pointer to a data type is so that it knows how many bytes the data is stored in. When we increment a pointer we increase the pointer by one ``block'' memory.
So for a character pointer ++ch_ptr adds 1 byte to the address.
For an integer or float ++ip or ++flp adds 4 bytes to the address.
Consider a float variable (fl) and a pointer to a float (flp) as shown in 
 
Pointer Arithmetic Assume that flp points to fl then if we increment the pointer ( ++flp) it moves to the position shown 4 bytes on. If on the other hand we added 2 to the pointer then it moves 2 float positions i.e 8 bytes as shown in the Figure.



Pointers and Arrays

Hint: think of array elements arranged in consecutive memory locations.

Consider the following:


   int a[10], x;
   int *pa;
 
   pa = &a[0];  /* pa pointer to address of a[0] */
 
   x = *pa;
   /* x = contents of pa (a[0] in this case) */
 
  Arrays and Pointers
To get somewhere in the array using a pointer we could do:

   pa + i $\equiv$ a[i] 



There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things.

For example we can just type

   pa = a;

instead of

   pa = &a[0]

and

   a[i] can be written as *(a + i)
i.e. &a[i] $\equiv$ a + i.  

We also express pointer addressing like this:

   pa[i] $\equiv$ *(pa + i)

However pointers and arrays are different:
  • A pointer is a variable. We can do
    pa = a and pa++.
  • An Array is not a variable. a = pa and a++ ARE ILLEGAL. 

Multidimensional arrays and pointers

We should think of multidimensional arrays in a different way in C:

A 2D array is really a 1D array, each of whose elements is itself an array

Hence

  a[n][m] notation.

Array elements are stored row by row.


Consider int a[5][35] to be passed in a function:

We can do:

   f(int a[][35]) {.....}

or even:

   f(int (*a)[35]) {.....} 
These both are same.
 


We need parenthesis (*a) since [] have a higher precedence than *

So:

   int (*a)[35]; declares a pointer to an array of 35 ints.  

  int *a[35]; declares an array of 35 pointers to ints.  
Understand the above eg, carefully as this might be confusing.


 char Aname[10][20]; 
Aname has 200 elements.
access the elements via 
 20*row + col+bas+address
in memory

char *name[10];
name has 10 pointer elements.
each pointer element can point to arrays of different length.

Consider the below :



char *name[] = { ``no month'', ``jan'',
    ``feb'', ... };
   char Aname[][15] = { ``no month'', ``jan'',
    ``feb'', ... };
 
2D Arrays and Arrays of Pointers
 name points to array of 13 elements  which in turn hold reference (address ) 13 arrays.
no month\0 is one array that name[0] is pointing to.
similarly jan\0
(Notice Each string ends with '\0' . String is an array of char type )
Consider the below example:



What happens when we declare a one dimensional array in memory.
in A[5]
mem location:
    200   204  208  212 216

 -----------------------------------------
   |2  |  4  | 6  | 8  | 10 |
------------------------------------------- 
    ^     ^     ^   ^     ^
    |     |     |   |     |   
   A[0]  A[1] A[2] A[3]  A[4]

contiguous block of memory 
integer is stored in 4 bytes ( block of four bytes) 

int *p = A;
address of array A will stored in p so aestrick upon a variable is used to hold 
value of address.
now we can by using d-referencing  technique get other elements of the array A.
eg:
print( p ) // Will give address of Array A 1.e 200
print( *p ) // will print the value at 200 memory location i.e 2 
          // Above is what is called d-referencing a pointer using * with         //address will give us the value at that address
print(*(p+2) )// will print 6 . This addition of 2 to integer pointer variable   
              //means we will hop two times from starting aadress
              // in address if we add anything suppose 2 or 3 what it does is 
              //adds 2*(no of bytes occupied by one element) here 4 bytes
              // occupied by each int element so 2*4 = 8 
              // 200+8 is 208 so p+2 is 208 and *(p+2) is the value at
              //208 i.e 6/


C gives us the flexibility of using array name instead of pointer variable.
Remember: Name of the array returns the address to the first element in the array.
So print( p ) is same as print(A)
similarly 
*A will print the value at A i.e 2.
*(A+2) will give us 6.

*(A+i) is same as A[i] .( where i being any number in the range of array i.e 
                           0 to n , n being the length of array )
A+1 is same as &A[i] . both will give us the address of the i th element.

Imp thing to note is 

int *p;
we can do p = A;
but not 
A=p; //will give compilation error

 

Two dimensional array.
int B[2][3];
here we are creating arrays of array 
in this case we are creating 2 one dimensional array of length 3.
B[0] -- an array of 3 elements so will occupy 3* 4 bytes( 4 because 
        each int element will occupy 4 bytes each ) so 12 bytes tot
B[1] -- another array of 3 elements.

   400            412
 -----------------------------------------
    400    404   408
   |  2  |3  | 4 | 5 | 6 | 7  |
    ^
  B[0][0]
------------------------------------------- 
    ^              ^ 
    |              |
   B[0]            B[1]


 int *p = B // compilation error as B will return pointer to a 1D array.

int (*p)[3] =B ;// This now correct as p will be able to hold what B returns
               // that is pointer to a 1 D array of 3 elements.
 


print(B);     // same as &B[0] that is 400

print(*B);    // same as &B[0] or &B[0][0] 400

print(B+1);   // B returns array of 3 integers 
              // adding 1 to that is like 
              // hoping the 3 elements 
              // B is 400 add one is 
              // hoping 3 int elements
              // 4*3 =12
             //412
         /// Don't get confused as this is a 2d array 
        // remember as b returns array of 3 so adding one to B will 
           //let us hop 1st row and go to next row.

print( *(B+1)); // same as B[1] or &B[1][0] ,B+1 returns a pointer to the 
                //  1 d array of 3 elements as shown above so 412 

                // *(B+1) is similar to int *p = &B[1][0]

print (*(*B+1)) ; // *B is same as &B[0] as we see above 
                  // adding one to that is same as adding 1 to memory address 
                  // of &B[0][0] which will give 404 
                    // Now *(&B[0][0]) which is we are dereferencing address 404 
            /// it will give us 3.
print ( *(B+1)+2)    // same as &B[1][0] add 2 to it is 412 + 2*4 ( int elements 
                     // has 4 bytes == 420


Point to remember

for a 2-d array 
B[i][j] where i and j are some indices in the array is same as 

B[i][j] == *(B[i]+j)

B[i][j] == *(*(B+i)+j)

























courtesy: http://www.cs.cf.ac.uk/Dave/C/node10.html




 

Monday, February 2, 2015

SQL Beginner

Sql is a standard language for accessing database eg: MySQL, SQL Server, Access, Oracle, Sybase, DB2.
SQL stands for structured query language.
Let us access database.
Is used for querying the database,
Insert,Update,Delete,create and manipulate database.

RDBMS
Relational Database Management System.
It is the basis of all database system
The data in RDBMS is stored in a db Object called Table
Table contains related data , it consists of columns and rows.
Following is a table customer in Database
CustomerId CustomerName
1 sunny
2 shekhar


Select * from customer 
 o/p
CustomerId CustomerName
1 sunny
2 shekhar





Monday, July 8, 2013

Swt Tables setting the check box in cetre of the cell

tbleViewer.getTable().addListener(SWT.PaintItem, new Listener() {
 ......
.......

 int tmpWidth1 = 0;
                int tmpHeight1 = 0;
                int tmpX1 = 0;
                int tmpY1 = 0;
                tmpWidth1 = tbleViewer.getTable().getColumn(event.index).getWidth();
                tmpHeight1 = ((TableItem)event.item).getBounds().height;
       
                tmpX1 = tmpImage1.getBounds().width;
                tmpX1 = (tmpWidth1 / 2 - tmpX / 2);
                tmpY1 = tmpImage1.getBounds().height;
                tmpY1 = (tmpHeight1 / 2 - tmpY / 2);
                if(tmpX1 <= 0) tmpX1 = event.x;
                else tmpX1 += event1.x;
                if(tmpY1 <= 0) tmpY1 = event.y;
                else tmpY1 += event.y;
                event1.gc.drawImage(tmpImage1, tmpX1, tmpY1);

Courtsey : Read it somewhere on the internet and this stuff works .Full credit to the unknown author of this code ...

Friday, June 14, 2013

Endings


Endings are very important part for any story probably the only part that matters .
A story with solid ending is always a superhit .
Here is a flop story , a story which should have never happened ,because it brought only sorrow guilt and nothing else .
Sammer loved a girl name shweta . They were quite close to each other . Their love story almost went for over 6 years . Even though it was a long distance love story ,they always felt each other's company .
Cracks had started coming through after end college and start of professional life . Gestures made more sense that feelings . Giving time to each other was very difficult for them ,even though they had plenty for time  .There were tensions in the family as well . One day family agreed but she refused , Shweta had shown how unpredictable a girl can be . Fate played its part in dividing them . Its been almost three years since the breakup
still sameer remembers her .Still is not able to understand whose fault is it . He always asks himself some questions . Some questions which he never gets the answers to .
How ever good the story is if ending is not good then all work done is gone .
How ever truly you love somebody , how much but if you are not together with each other then its of no use.
Why is it that only Sameer had an unsuccessful love story and not others . People around him all have successful love story . Sameer ponders sometimes whether  he did something wrong to deserve this , or did he love the wrong person . Whom to blame ? Or is it that he should have never loved anybody .Generally he blame himself for this .
He feels that he was weak , his love was not strong enough to hold her near him .He let her go .Why did he  do so .
Fate never wanted them together , in the end he played in the fate's hand He read some where that if true love is there it will surely find a way back in . he also tried that but it never returned back . It went and went far and far away from him never to return back ,. here he is sitting alone in the theater , in the park , his bike's pillow seat is always empty . No one to hold hand and console him  . There is something left in his heart , some memories , some faint pictures of his love ,some moments they shared . A beer will do tonight not to forget her but just to go near those memories deep inside his heart be there for sometime no one to disturb .
He have learnt somethings , If you gonna love some day some body be sure to be with him/her till the end ,don't leave him in between .
Sameer probably won't love anybody as he used to love her . He always feels that he is weak , guilty .
I never think that sameer was wrong in what he did ,but you can't make sameer understand .The fault was the with the one who was not able to stand up with him . How can sameer expect her to stand with him through out his life .
Make sure that there is proper ending to your story . Don't leave the story unfinished .

Friday, April 19, 2013

Creating SWT table


                    SWT TableViewer

Below I will try to explain you as to how to create a SWT table .
1.Set the layout on the composite over which you wanna create the Table specifying width and height etc .

2. Create a table
         TableViewer tableViewer = new TableViewer(parentComposite,SWT.BORDER );

3.Set the content provider
          tableViewer.setContentProvider(new TableContentProvider())
here TableContentProvider is implemeting IStructuredContentProvider
its method : public Object[] getElements(Object inputElement)
 Returns the elements in the input, which must be either an array or a Collection
So what ever you set as Input in the table we must convert it into array of objects here .

4. Set the LabelProvider  :tableViewer.setLabelProvider(new tableLabelprovider())
         tableLabelprovider    implements ITableLabelProvider
Here we can override two methods
  public String getColumnText(Object element, int columnIndex) : Returns the label text for the given column of the given element.
 Get the model which you setting in the table as input from element and using switch case we can return the value for each column according to the column Index
this is to set the label for each field in your table

5.Add columns according to your requirement

6. If you want any kind of cellEditor eg:TextCellEditor ,CheckboxCellEditor,Dialog cellEditor ,then you have  to add CellEditors for each column . If you want your column to be editable then we can use TextCellEditor .
7. set a cellModifier to your table viewer .
here in the method canModify we have to return true if for a particular column you want it to be editable .
in the method getValue() return value from your model according to the column (property name )
in the method modify() get the value from the table that has been modified and set it to your model and save the model accordingly .
Remember to refresh your table viewer .




Monday, April 8, 2013

Creating quick fix extension for Eclipse Below i am listing the steps needed for creating quick fix extensions in eclipse . I am assuming that the problem has already been registered with eclipse 1.Create a marker type with extension point org.eclipse.core.resources.markers 2.Extend the org.eclipse.ui.ide.markerResolution extension point and create a markerresolutiongenerator . 3.add the marker type while creating the validation error in the code . 4.Create a class resolution generator implements IMarkerResolutionGenerator and register it to plugin while extending the extension point markerResolution . 5.In the function getResolutions(IMarker marker) return a new object which implements IMarkerResolution2 . 6.In the run function do the necessary work . 7.Use other methods such as getDescription() etc to make ur quick fix more informative

Wednesday, March 20, 2013

Happy Bday Dear !!

Last week was my friends birthday , one of the closest , who shares almost everything . As usual people wished him , he got gifts ,cake cutting , friends ko party bhi di .
Phir bhi kuch kami si mehsus ho rahi thi was his exact words that evening .There was something missing . Why was this different if you ask me then nothing much only that a person used to call him sharp at 12 'o clk , would fight if somebody else wished him before her .A gift not very costly but would make him very happy .Par aaj wo nahi hain uske pas . She is not there to pamper him , fight with him , tease him ...
He often ask this question to himself , why he need some one in his life .Now he have freedom ,no restrictions ,just   like khula sandh .. no one going to get angry if he sleep before 12 o clk or if  he go out with his friend(most of the times with me :) ) and stay late without calling her . No fights with his  parents over the issue of marriage . No one in the society is going to point a finger at him . If there are so many  (+)ves out of being single then why he still feel the emptiness . Why he cry when he watches  a romantic movie .Why he still wakes up in the night and check for missed calls . Why he  crave for her so much .He  doesn't have the patience to deal with a new relation but still some where in his heart he wants it . He wants it badly . May be its just the hormones playing its part . May be seeing others getting settled .He feels that he has missed something big in his life .

This word LOVE  confuses me a lot . It gives a lot of pain , a bit of happiness but still every body wants it. May be our mind is designed insanely to crave for it .
ps: I feel pity on my friend . Its his feeling and and my words .  So all people who still have their loved  ones beside you holding ur hands at every moment of ur life cherish it because it feels much more worse than what i have written .Hope i never have to through what my dearest friend went through .