Multi Dimensional Array Data Structure in C(2D)

An array can be created in a matrix form too with n number of rows and m no of columns.

Implementation of 2D array in C language

There are 3 ways to implement 2 Dimension Array.

  1. Simple initialisation
int a[5][10];

This will create an array matrix of row length 5 and column length 10.

a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;

All arrays are in stack.

2.Array of pointers

In this type of initialisation we initialise an array of pointers and then each pointer in this array of pointer points to a new array.

    int *p[3];
    p[0]=(int*)malloc(3*sizeof(int));
    p[1]=(int*)malloc(3*sizeof(int));
    p[2]=(int*)malloc(3*sizeof(int));
    p[0][0]=5;
    p[0][2]=5;

And then this can be used like the simple 2D array. Accessing elements also the same way like 2D array.

Arrays of pointer that are rows are in stack and columns arrays associated with each row array is in main/heap memory.

3. Pointer to a pointer

We initialise a pointer to a pointer.

    c=(int**)malloc(2*sizeof(int));
    c[0] = (int*)malloc(2*sizeof(int));
    c[1] = (int*)malloc(2*sizeof(int));
    c[0][0]=1;
    c[0][1]=2;
    c[1][0]=3;
    c[1][1]=4;

c is a pointer to a pointer. c[0] represents pointer to the first row, similarly c[1] to the second row. c[0][1] represents the element of first row and second column.

Here only c is created in the stack, and all arrays in the main/heap memory.

LEAVE A REPLY