Tuesday, July 14, 2009

How to work with c pointers?

A pointer refers to an address that points to another variable.





So say you have an integer x, and another integer y.





int x, y;





You might have a pointer to the "current" integer:





int *current;





Now you could write something like this:


current=%26amp;x; /* make current point to x */


*current=5; // set x to 5





The advantage here is that you can later set current to %26amp;y and then code that used to modify x will now modify y.





This is useful in functions where you want to modify an argument. For example:





void square(int *x)


{


*x=*x * *x;


}





You might call this as:


int z=50;


square(%26amp;z);


/* now z= 50*50 */





Of course your could write square in this case to return the result, but perhaps you are returning some result already and want to return something else. For example, suppose you want to write a function that gets two numbers and returns the largest and the smallest, you might write:





int numsort(int a, int b, int *smallest)


{


if (a%26gt;b) { *smallest=b; return a; }


else { *smallest=a; return b; } /* if equal, doesn't matter */


return 0; // not reached


}





Another important use is when working with arrays. An array name is a pointer to the first element of the array:





int x[50];





You can even have pointers to functions. For example, you might have a table of function pointers to execute different code based on an index.





Now x is the same as %26amp;x[0] and incrementing x will point at subsequent elements.





Finally, dynamic allocation uses pointers. So another way to handle the array above would be:





int *x;


x=malloc(50*sizeof(int)); /* make array of 50 integers */


/* Now x works just like an array */


. . .


free((void *)x);

How to work with c pointers?
You can also have pointers to functions. Take the addresses of various functions and put them in an arrays of function pointers.


This is useful in implementing state machines and executing different functions according to rules built around calculations rather then if..then..else constructs
Reply://Declare a pointer





int *i; // just prefix a normal variable with *





//Once you are done with your pointer just delete it


delete i;





// to access member functions in pointers use "-%26gt;" instead of "."





this-%26gt;setText("hello");





Note: This is c++, c uses the same conventions with the exception of "//" = "/* */"

land survey

No comments:

Post a Comment