Pointers in C – 1

Variables, constants, functions etc are stored in the RAM(Random Access Memory) of a computer. If we define two variables x and y then they would have to be stored at some memory location.
Pointer manipulation is done using two operators * and &. * gives the value stored at an address, while & gives the address of a variable.
Consider the following program.

#include<stdio.h>
#include<conio.h>
void main()
{
int x=1,y=2;
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();
}

c output pointers

The address is printed using %u. This stands for an unsigned int. &x gives the address of the variable. As we can see the difference between two addresses is 2. This means that an int requires 2 bytes for storage.

Defining Pointers
To define pointers we will write:

 int *p;

This means that *p is an integer, while p is a pointer to int meaning it holds the address of an int.
*p means the value at address p. This means that using *p we can actually get the value at the address and also modify it. Let us try a program where we will actually change the value of a variable.

#include<stdio.h>
#include<conio.h>
void main()
{
int x=1;
int *p;
clrscr();
p=&x;
printf("Value of x=%d, address of x=%u\n",x,p);
*p=2;
printf("Value of x=%d, address of x=%u\n",x,p);
getch();
}

C pointer output

Leave a Reply