What are Pointers in C?

This is an introductory post explaining pointers in the C Programming Language.

Pointer: A Pointer is the address of a variable, constant or function. In this post we will concentrate on variables.
Every variable declared is given an address, a value and a name.

Operators in pointers.
Pointers have 2 operators.
1. * operator. Gives the value at an address.
2.& operator. Gives the address of a variable

The following program prints the address and value of two integer variables. Notice that we use %u = unsigned int for the address.
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5,y=7;
clrscr();
printf(“Value of x=%d, address of x=%u\n”,x,&x);
printf(“Value of y=%d, address of y=%u\n”,y,&y);
getch();
}

basic pointers program-basic pointers program output

 

Defining pointers. We define a pointer to integer by writing:
int *p; Here *p is an integer and p is pointer to integer.
Consider the following program snippet.
int x=5,y=7;
int *p1,*p2;

Let us imagine x is stored at address 1000 and y at address 1002.
Writing p1=&x; will assign p1 to address of x =1000. Similarly, p2=1002,
Now *p1=*1000 = value at address 1000=value of x =5. By the same logic *p2=7.
The following program illustrates this:

#include<stdio.h>
#include<conio.h>
void main()
{
int x=5,y=7;
int *p1,*p2;
clrscr();
printf(“Value of x=%d, address of x=%u\n”,x,&x);
printf(“Value of y=%d, address of y=%u\n”,y,&y);
p1=&x;
p2=&y;
printf(“Value of p1=%d, value at address pointed to by p1=%u\n”,*p1,p1);
printf(“Value of p2=%d, value at address pointed to by p2=%u\n”,*p2,p2);
getch();
}

basic pointers program 1 basic pointers program output 1

 

Declaring pointers to pointers. If we write int **q;
Then **q is an int.
*q is pointer to int.
q is pointer to pointer to int.

Here is another program illustrating this:

#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
int *p;
int **q;
clrscr();
p=&x;
q=&p;
printf(“x=%d, *p=%d, **q=%d\n”,x,*p,**q);
printf(“&x=%u, p=%u, *q=%u\n”,&x,p,*q);
printf(“&p=%u, q=%u\n”,&p,q);
getch();
}

pointer to pointers programpointer to pointers output program

 

Leave a Reply