Credits

Sunday, March 1, 2009

Pointers of C

Pointers are more flexible and fast to manipulate than arrays although they are also dangerous if not properly
handled.

Compare the array and pointer definitions below:
char str[80],*p1;
p1=str; /* in this line, the value of the first element is passed to the pointer p1*/

to access the element,example, element 5, write your array and pointers statements like these:
array: str[4]; /*since the first element is indexed at 0*/
pointer: *(p1+4)

The operators used in pointers are * and & where
* is used to access the value while & on the memory address. Check the program below:



[+/-] show/hide



#include stdio.h /*enclose this in <>*/
main()
{
int x=10,y;
int *p1;
p1=&x; /*the memory address of 10 is assigned to pointer p1*/
y=*p1; /*the value of p1 is assigned to y*/
printf("The element %d is at location %p",y,p1);
getche();
}

The output of this is:
The element 10 is at location (not specific).

AddThis