February 15, 2016

Pointer usage in C

C provides pointers which are used to store the address location of another variable of a particular data type.

Declaring a pointer to an integer variable,

int *p;

where, 'p' is a integer pointer that can point to (store the address of) a variable of type 'int'.
i.e., an integer pointer should be used to store the address of an integer variable only.

Similarly, a character pointer shall point to a character variable only. Failing to follow this, may result in an undefined behaviour.

Now, lets consider an example:

#include <stdio.h>

int main(void)
{
    int a = 10; /* An integer variable */
    int *p; /* A pointer to an integer */

    p = &a;

    printf("a = %d  *p = %d\n", a, *p);
} 

Output:
a = 10 *p = 10

In the above program, integer 'a' will be allocated a memory in stack say '0x1000' and the value '10' is stored in that memory location. Integer pointer 'p' will be allocated a memory in stack say '1004'.

Now, '&a' represents the address allocated to store the value in 'a' i.e., &a = 1000.

Now, this value 1000 is copied to 'p'. Now, the variable 'p' contains 1000.

Then, in the print statement, '*p' means de-referencing 'p'.

i.e., contentof(p) or contentof(1000) = 10. Hence, the output 10.

With this understanding, lets look at how to use double pointers and dynamically allocate a memory in the next example.

No comments:

Post a Comment

Comment will be published after moderation only. Do not advertise here.