POINTERS IN C

• Variables are allocated memory space in main
memory/primary memory, to store their
values.
• Main memory is partitioned into cells called
memory cells/memory word .
• Each memory word is given address which is
numerical that ranges from 0 , 1, 2 ….• Pointer is a data type
• Value of pointer variable is memory address which is
numerical value
Declaration
int *P1;
P1 is a pointer variable pointing to integer
value of P1 is memory address of int variable
• Address operator
int x;
&x refers to address of x
Address of x can be assigned to a pointer variable
ex: P1=&x

#VOID POINTER

void pointer is a special type of pointer.
Void pointer can point to a variable of any data type,
integer , float ,character.
– The type casting or assignment must be used to turn the
void pointer to a pointer of a concrete data type to which we
can refer.
– limitation is that the pointed data cannot be referenced directly
(the asterisk * operator cannot be used on them) since its length is
always undetermined.

Example

include

int main()
{
int a=5,
double b=3.1415;
void vp;
vp=&a;
printf(“\n a= %d”, *((int
)vp)); // type casting to int pointer
vp=&b;
printf(“\n a= %d”, *((double *)vp));
// typecasting to double pointer
return 0;
}
OUTPUT:
a= 5
b= 3.141500

One dimensional Arrays & pointers:

• Array name is address of first element. So array name
is a pointer
• We can access array elements using array name
without using subscript
Int x[5];
x refers to address of 0th element
x+1 refers to address of 1st
element
…..
x+n-1 refers to address of (n-1)th or last element

// accessing array elements using array name which is a pointer

include

include

main()
{
int a[5]={10,20,30,40,50};
clrscr();
printf("address of a[0]=%p a[1]=%p a[2]=%p\n",&a[0],&a[1],&a[2]);
printf("address of the first element of array=%p\n",a);
printf("value of first element=%d value =%d\n",a[0],a);
printf("value of second element=%d value=%d\n",a[1],
(a+1));
printf("value of last element=%d value=%d\n",a[4],*(a+4));
return;
}

Accessing array elements using pointer

include

int main()
{
int i,a[7]={1,2,3,4,5,6,7};
int p;
p=a; // array name is a pointer to the first element
for(i=0; i<7; i++)
printf("%d\t",
(p+i)); //adding i value to pointer p
return(0);
}

Operations on pointer variables:

• Pointer variable can be assigned with NULL
ex: int *x=NULL
• Pointer variable can be initialized with another pointer or with address of
another variable
Ex:
float x;
float *p1=&x, *p2=p1;
• Integer constant can be added to a pointer. This is useful for accessing
array elements
Ex:
int a[5]={1,2,3,4,5}
int *p1=a;
p1=p1+2 refer to third element of array

14