Go back

Data Structures and Algorithms - Pointers

What are pointers?

Poitners are varables which store memory address. This memory address can be used to access and modify the value stored in that memory location.

Pointer to array

The array variable by default can be used as a pointer to the base address.

We can perform basic pointer manipulation to access any index in an array.

Accessing index using pointer in 1D array

int a[] = {2,3,6,7};
//if we want to access the element in index 2
printf("%d", *(a+2));

2D array and accessing using pointers

int a[][3] = {{1,2,3}, {4,6,7}};
//if we want to access the element in index 2 of index 1
printf("%d", *(*(a+1)+2));

Did you know these about 2D array in C

  1. 2D array in C are row major so the first index denote the row and the second index denote the column inside the row.

  2. When initializing a 2D array you need to provide the number of columns (max number of elements in the rows)

malloc

malloc is a function we can use to allocate memory in C. This memory is allocated on the runtime, and this phenomenon is known as runtime memory allocation.

The function malloc belongs in the #includ<stdlib.h>

malloc by default returns a void pointer.

You can typecast that pointer to any data type.

Example -

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *x = (int*)malloc(sizeof(int));
    *x = 100;
    printf("Value: %d\n", *x); 
    return 0;
}

Null pointer vs void pointer vs dangling pointer

Null pointer points to nothing and can be declared as below -

int *p = NULL;

Void pointer is a pointer which can hold address of any type. malloc by default returns void pointer. If properly typecased void pointer can be used safely. Example -

int x = 42;
void *vp = &x;
printf("Void Pointer: value = %d\n", *(int*)vp);

Dangling pointer is a pointer which was used to point to a memory location but the memory location has since been freed / out of scope. Example -

int *dp = (int*)malloc(sizeof(int));
*dp = 100;
free(dp);     // memory freed
// dp still points to freed memory which makes it dangling
printf("Dangling Pointer: %d\n", *dp); //this is not safe to do and leads to unstable behaviour