C Programming language

Pointer in C
Previous Home Next

Pointer in C

C pointer is a memory address. for example:

int x = 10; 

You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator &; before it.

printf("memory address of x is %d\n",&x);

and in my PC the output is

memory address of x is 1310588

To access memory address of variable x you have to use pointer.

To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows:

int *px;
Now  pointer px to points to memory address of variable x,
you can use address-of operator (&)
int *px = &x; you can change the content of variable x for example you can
increase, decrease x value :
*px += 10; printf("value of x is %d\n",x); *px -= 5; printf("value of x is %d\n",x); the output indicates that x variable has been change via pointer px. value of x is 20 value of x is 15

It is noted that the operator (*) is used to dereference and return content of memory address.

In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address. In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows:

 int c = 10;
 int c2 = 20; .
    /* define a pointer and points to an constant integer.
    pc can point to another integer but you cannot change the
    content of it */
 const int *pc = &c;
   /* pc++; */ /* cause error */ 
 printf("value of pc is %d\n",pc);
 pc = &c2;
 printf("value of pc is %d\n",pc);
    /* define a constant pointer and points to an integer.
   py only can point to y and its memory address cannot be changed
   you can change its content */
 int y = 10;
 int y2 = 20; 
 int const *py = &y;
 *py++;/* it is ok */
 printf("value of y is %d\n",y); 
   /* py = &y2; */ /* cause error */

 value of pc is 1310580
 value of pc is 1310576
 value of y is 10
Previous Home Next