Definition of a Pointer

Definition of a pointer in C


Introduction

Let us consider the following statement:

int i=20 ;

It instructs the compiler:

- To reserve sizeof(int) memory space

- Name the reserved space as i

- store value 20 at the address/location of i

The memory map for given variable i is as follow:

we can get the above information using following code:

#include <stdio.h>
int main() {
    int i = 20;
    printf("\n Value of i= %d\n", i);
    printf("\n Address of i = %u\n", &i);
    return 0;
}

Output:

 Value of i= 20

 Address of i = 1835169048

Here in the statement,

printf("\n Address of i = %u\n", &i); 

the operator & is called as the address of operator. Since addresses are always whole numbers with no sign assigned to them, we use %u format string for such unsigned values. 

Now, we can collect address of a variable in another variable as follows:

// address of i is assigned to variable j
j = &i; 

Here , j is not a normal variable, it is holding the address of integer variable i. Since all the variables in C need to be declared first before its use. Hence, the variable j is defined as pointer variable here, using following syntax:

// here J is a pointer variable. 
int i=10, *j;
// here j stores address of integer variable i
j = &i;

Here the operator * is called as value at address operator. When associated with any address the * operator also called as indirection operator, returns value stored at that location.

Definition of pointer in C

By using the above concept, Pointer  can be defined as a variable that holds the address of another variable. 

Now let us understand the concept of pointer using following program:

#include <stdio.h>
int main() {
    int i = 20,*j;
    // j is a pointer variable 
    j = &i;
    printf("Value of i= %d\n", i);
    printf("Address of i = %u\n", &i);

    printf("Value of i= %d\n", *(&i));
    printf("Address of i = %u\n", j);

    printf("Value of i= %d\n", *j);

    return 0;
}

Output:

Value of i= 20
Address of i = 1799386392
Value of i= 20
Address of i = 1799386392
Value of i= 20