Pointers

1. Pointers

1.1. Definition

Pointers store the address of variables or a memory location.

Pointers overview

1.2. To Use Pointers in C, We Must Understand These Two Unary Operators (* and &)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include<stdio.h>

int main()
{
    int x = 10;
    int *prt;

    /* The & operator before x is used to get
     * the address of x and then this address
     * is assigned to ptr. */
    ptr = &x;

    return(0);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include<stdio.h>

int main()
{
    int x;

    /* Prints the address of x */
    printf("%p", &x);
    return(0);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include<stdio.h>

int main()
{
    int x = 10;
    int *ptr = &x;

    printf("Value of x = %d\n", *ptr);
    printf("Address of x = %p\n", ptr);

    *ptr = 20;
    printf("After doing *ptr = 20, now *ptr is %d\n", *ptr);
    printf("After doing *ptr = 20, now x is %d\n", x);

    return(0);
}

Please refer to the picture below to gain a better understanding of what this code is doing.

Pointer visualization

1.3. Pointer Expressions and Pointer Arithmetic

A limited set of arithmetic operations can be performed on pointers. A pointer may be:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include<stdio.h>

int main()
{
    int v[3] = {10, 20, 30};

    int *ptr;
    ptr = v;

    for (int i = 0; i < 3; i++) {
        printf("Value of *ptr = %d\n", *ptr);
        printf("Value of ptr = %p\n", ptr);
        ptr++; /* Increments pointer ptr by 1 (the size of an integer = 4) */
    }
}

1.4. Array Name as Pointers

An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named v, then v and &v[0] can be used interchangeably.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include<stdio.h>

int main()
{
    int v[3] = {10, 20, 30};
    int *ptr;
    ptr = v;  /* The same as ptr = &v[0]; */

    printf("The elements of the array are: %d - %d - %d\n", ptr[0], ptr[1], ptr[2]);
}

1.5. Pointers and Multidimensional Arrays

A pointer notation for the two-dimensional numeric arrays, consider the following declaration

1
int nums[2][3]  =  { {16, 18, 20}, {25, 26, 27} };

In general, nums[i][j] is equivalent to *(*(nums+i)+j)

Array NotationPointer NotationValue
nums[0][0]*(*nums)16
nums[0][1]*(*nums + 1)18
nums[0][2]*(*nums + 2)20
nums[1][0]((nums + 1))25
nums[1][1]((nums + 1) + 1)26
nums[1][2]((nums + 1) + 2)27