C Pointers


C language allows us to refer to a memory location by its internal address or byte number by using pointers. A pointer is a variable that contains the address of a variable. Value stored in a variable is accessed through the address of the memory location where the variable is stored. Pointer is often considered by the programmers as the toughest topics of C language but its clear understanding gives a strong hold on system programming.
To get address of x (variable) we use the operator ’&’ ampersand.

&-address operator

Address operator returns the address so its value is stored in another variable i.e. ptr. Therefore ptr refers to address of x and not its value.

Declaration of pointer

Pointer (ptr) variables must be declared before it is used in a program. So a variable name is preceded by (*) asterisk.

int *ptr;

note: *ptr is invalid because it does not indicate the type of variable it indicates.
Here is short program that will help us in understanding the concept of pointers clearly.
# include
# include
int a=5;
int *ptr; /*declaration of pointer variable */
printf(“\n value of a=%d”,a);
/* output – 5 */
Printf(“\n address of a=%d”,&a);
/* output- 1056(random value i.e. : the address of the variable stored) */
Printf(“address of a=%d”,ptr);
/* output-1056(same as above) */
Printf (“\n value of a=%d”,*ptr);
/* output- 5 */

Manipulation of pointers

The above example shows that the value stored in variable can also be accessed by the unary operator ‘*’. Therefore x and *ptr point to the same data item.
Pointer variables are also same as other variables in the fact that they can also be equated like other variables. Consider the following example:

int a,b,*p1,*p2;
printf(“a=%d b=%d”,*p1,*p2);
/*output- a=2 b=4 */
*p2=*p1 /* p2 gets the value of p1 */
Printf(“a=%d b=%d”,*p1,*p2);
/*output- a=2 b=4 */
Printf(“a=%d b=%d”,a,b);
/* output- a=2 b=2 */
p2=p1; /* p2 also points to which p1 points */
printf(“ a=%d b=%d”,*p1,*p2);
/* output- a=2 b=2 because p2 also points to which p1 points */
Printf(“a=%d b=%d”,a,b);
/* output- a=2 b=4 */
/* value of b is still 4 */


Related Articles: