C examples for Pointer:Pointer Variable
Place the indirection operator * in front of the variable name to declare a pointer.
Pointer variables must be declared before they can be used:
#include <stdio.h> int main()/*from ww w . jav a 2 s . c o m*/ { int x = 0; int iAge = 30; int *ptrAge; }
To indirectly reference a value through a pointer, you must assign an address to the pointer.
ptrAge = &iAge;
In this statement, I assign the memory address of the iAge variable to the pointer variable ptrAge.
The unary operator & is referred to as the "address of" operator.
You can assign the contents of what the pointer variable points to-a non-pointer data value.
x = *ptrAge;
The variable x will now contain the integer value of what ptrAge points to-in this case the integer value 30.
Pointer variables should be initialized with another variable's memory address, with 0, or with the keyword NULL.
The next code block demonstrates a few valid pointer initializations.
#include <stdio.h> int main()/* w w w . j a v a 2s .co m*/ { int *ptr1; int *ptr2; int *ptr3; int x = 5; ptr1 = &x; ptr2 = 0; ptr3 = NULL; printf("point variable defined."); }
Assign address to pointer
#include <stdio.h> int main() { int x = 5; int *iPtr; iPtr = 5; //this is wrong iPtr = x; //this is also wrong iPtr = &x; //iPtr is assigned the address of x *iPtr = 7; //the value of x is indirectly changed to 7 printf(""); }