Pointers in C

Pointers in C



Pointers in C are variables which point to another variables.
For declaring pointer we need to use * symbol.

Syntax for declaring pointer:
 Data_type *pointer_name;

Data type of pointer must be same as that of variable to which it is pointing.
But, void type of pointer works with all types of variables.

We use address of i.e & operator in C to initialise value to pointer.
e.g:
int a=20;
int *ptr;
*ptr=&a;              or           ptr=&a;

What happens within memory?



Suppose we declare:
int a=20;
int *ptr;
*ptr=&a;
Then as seen in above memory diagram, memory will be first allocated to variable a say at address location 256.
Then memory will be allocated to ptr variable at address location 524 (say).
Now, as we have declared and initialised variable a it has value 20.
But, we have only declared ptr not initialised it so it will have some garbage value in it.
But, by 3 line of our code we have initialised ptr content to address of a.
So, now diagram will be clear to you.

Suppose further more 3 lines of code is written as:
printf(“%d”,a);
printf(“%d”,&a);
printf(“%d”,ptr);
printf(“%d”,*ptr);

So, by our regular convention output of 1st line will be 20.
Output of 2nd line will be address of a i.e. 256.
Output of 3rd line will be value which ptr holds i.e. 256.
Output of 4th line can be interpreted as:
*ptr
But, ptr=&a
So, *ptr=*(&a)
But, &a is 256
So, *(256)
And content at 256 location is 20.
Thus, output of 4th line is 20.

Note: Similarly, we can have pointer pointing to another pointer too.





Let's see one more program:

#include<stdio.h>
void main()
{
int i=5,*j;
j=&i;
printf("Content of i is: %d",i);
printf("\nAddress of i is: %u",&i);
printf("\nAddress of i is: %u",j);
printf("\nAddress of j is: %u",&j);
printf("\nContent of j is: %d",*j);
}

Output:



No comments:

Post a Comment