0% found this document useful (0 votes)
47 views

Acces 2D Array

The document discusses several ways to access elements of a two-dimensional array using pointers in C. It explains that a 2D array can be accessed using a single pointer by calculating offsets based on the row and column. It also demonstrates how to access a 2D array using pointers to arrays, by defining a new type for the 2D array and creating a pointer to it. The document further discusses dynamically allocating 2D arrays on the heap using a single pointer, an array of pointers, or a double pointer approach. It also covers passing 2D arrays as parameters to functions.

Uploaded by

Adrian Iosif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Acces 2D Array

The document discusses several ways to access elements of a two-dimensional array using pointers in C. It explains that a 2D array can be accessed using a single pointer by calculating offsets based on the row and column. It also demonstrates how to access a 2D array using pointers to arrays, by defining a new type for the 2D array and creating a pointer to it. The document further discusses dynamically allocating 2D arrays on the heap using a single pointer, an array of pointers, or a double pointer approach. It also covers passing 2D arrays as parameters to functions.

Uploaded by

Adrian Iosif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

How to access two dimensional array using pointers in C

BY AMLENDRAON

https://aticleworld.com/access-two-dimensional-array-using-pointers-in-c/

I have written a lot of articles on array and pointer if you want you can see this link, C Tutorial.
Nowadays many students ask me a question that how to access a multidimensional array with a pointer.
I have replied many students but every week I found this question in my Inbox.

So I have decided to write an article on how to access a multidimensional array with a pointer. I am
assuming you are already familiar with a multidimensional array, if you don’t have the knowledge of
array, then you should check this article, brief introduction of an array.

Relationship between array and pointer


In C-language pointer and array are very close to each other, an array can be split in the form of the
pointer. The name of the array is a pointer to its first element.So if acData is an array of character then
acData will be the address of its first element. You can also say that acData is similar to the &acData[0]

Below expression describe a relation between array and pointer,

acData [i] = *(acData +i) ————————->1D array in form of pointer

a[i] = *(a+ i) ————————->ith element of an 1D array

acData [i][j] = *(acData [i]+j); ————————–>2D array in form of 1D array and pointer.

acData [i][j] = *(*(acData + i) + j) ———————->2D array in form of pointer.

Note: An array elements stored in a consecutive memory block, so we can access the elements of the
array using the pointer.

Access a 2d array using a single pointer


In C language, compiler calculates offset to access the element of the array. The calculation of the offset
depends on the array dimensions.

Let’s take an example,

Suppose int aiData[3][3] is a 2D array that has 3 rows and 3 columns. If you need to access the 2nd
element of 1 row in aiData, then calculates its offset that will be (1 * coloumb_number) + 2 ). Now to
access the element just add the offset in array base address and dereference it.
Note: Array index always start with 0, so 2nd means third element.

See the below steps for above description,

calculate offset => offset = (1 * coloumb_number)+ 2);

Add offset in array base address => (int *)aiData + offset; //here

typecast with int pointer because aiData is an array of integer

Get the element => *( (int *)aiData + offset );

See: Pointer arithmatic in C.

Note: General expression to calculates offset for 2D array is that, (ithRow * Total_number_Coloumb)+
jthColoumb).

#include <stdio.h>
#define R#include <stdio.h>

#define ROW 3

#define COL 3

int main(void) {

// 2d array

int aiData [ROW][COL] = { { 9, 6, 1 }, { 144, 70, 50 }, {10, 12, 78} };

int *piData = NULL; //pointer to integer

int iRow =0, iCol =0;

piData = &aiData[0][0]; //You can also write *aiData

for (iRow = 0; iRow < ROW; ++iRow) //Loop of row{

for (iCol = 0; iCol < COL; ++iCol)// Loop for coloum{

//Read element of 2D array

printf("aiData[%d][%d] = %d\n",iRow,iCol, *(piData + ( iRow * COL) + iCol));

return 0;

We know that array element is stored in the contiguous form so we can also access the elements of the
two-dimensional array to the calculate the total number of cells.

See the below program,

#include <stdio.h>
#define ROW 3 // number of rows in array

#define COL 3 // number of col in array

#define TOTAL_CELLS (ROW * COL) //totall cells in array

int main(void)

// 2d array

int aiData [ROW][COL] = { { 9, 6, 1 }, { 144, 70, 50 }, {10, 12, 78} };

int *piData = NULL; //pointer to integer

int arrayIndex = 0; //variable for array index

piData = &aiData[0][0]; //You can also write *aiData

for (arrayIndex = 0; arrayIndex < TOTAL_CELLS; ++arrayIndex) //Loop of row

printf(" array elements = %d\n", *(piData + arrayIndex ));

}
return 0;

If you want to learn more about the c language, here 10 Free days (up to 200 minutes) C video course for you.

Access 2d array using a pointer to an array


We can easily access a 2D array with the help of pointer to the array. First, we need to define a new type
for the 2d array using the typedef that helps you to avoid the complex syntax. If you don’t know typedef
see this article, application of typedef. After the creation of new type for the 2d array, create a pointer
to the 2d array and assign the address of the 2d array to the pointer.

#include <stdio.h>

#define ROW 3

#define COL 3

typedef int Array2D[ROW][COL]; //New type

int main(void)

// 2d array

Array2D aiData = { { 9, 6, 1 }, { 144, 70, 50 }, {10, 12, 78} };

Array2D *p2DArray = NULL; //Pointer to the 2d Array


int iRow =0, iCol =0; //Row and col

p2DArray = &aiData; //Assign address of array to the pointer

for (iRow = 0; iRow < ROW; ++iRow) //Loop of row

for (iCol = 0; iCol < COL; ++iCol)// Loop for coloumb

//Read element of 2D array

printf("aiData[%d][%d] = %d\n",iRow,iCol, (*p2DArray)[iRow][iCol]);

return 0;

Similar to the two-dimensional array we can access three, fourth, … etc dimensional array using the
pointers.
How to dynamically allocate a 2D
array in C?
Following are different ways to create a 2D array on heap (or dynamically allocate a 2D array).
In the following examples, we have considered ‘r‘ as number of rows, ‘c‘ as number of columns and we
created a 2D array with r = 3, c = 4 and following values
1 2 3 4
5 6 7 8
9 10 11 12

1) Using a single pointer:


A simple way is to allocate memory block of size r*c and access elements using simple pointer
arithmetic.

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

int main()
{
int r = 3, c = 4;
int *arr = (int *)malloc(r * c * sizeof(int));

int i, j, count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(arr + i*c + j) = ++count;

for (i = 0; i < r; i++)


for (j = 0; j < c; j++)
printf("%d ", *(arr + i*c + j));
/* Code for further processing and free the
dynamically allocated memory */

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12

2) Using an array of pointers


We can create an array of pointers of size r. Note that from C99, C language allows variable sized
arrays. After creating an array of pointers, we can dynamically allocate memory for every row.

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

int main()
{
int r = 3, c = 4, i, j, count;

int *arr[r];
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));

// Note that arr[i][j] is same as *(*(arr+i)+j)


count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count

for (i = 0; i < r; i++)


for (j = 0; j < c; j++)
printf("%d ", arr[i][j]);
/* Code for further processing and free the
dynamically allocated memory */

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12

3) Using pointer to a pointer


We can create an array of pointers also dynamically using a double pointer. Once we have an array
pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

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

int main()
{
int r = 3, c = 4, i, j, count;

int **arr = (int **)malloc(r * sizeof(int *));


for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));

// Note that arr[i][j] is same as *(*(arr+i)+j)


count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count

for (i = 0; i < r; i++)


for (j = 0; j < c; j++)
printf("%d ", arr[i][j]);

/* Code for further processing and free the


dynamically allocated memory */

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12

4) Using double pointer and one malloc call

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

int main()
{
int r=3, c=4, len=0;
int *ptr, **arr;
int count = 0,i,j;

len = sizeof(int *) * r + sizeof(int) * c * r;


arr = (int **)malloc(len);

// ptr is now pointing to the first element in of 2D array


ptr = (int *)(arr + r);

// for loop to point rows pointer to appropriate location in 2D array


for(i = 0; i < r; i++)
arr[i] = (ptr + c * i);

for (i = 0; i < r; i++)


for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count

for (i = 0; i < r; i++)


for (j = 0; j < c; j++)
printf("%d ", arr[i][j]);

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12

How to pass a 2D array as a parameter in C?


This post is an extension of How to dynamically allocate a 2D array in C?
A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a
function can be difficult to remember. One important thing for passing multidimensional arrays is, first
array dimension does not have to be specified. The second (and any subsequent) dimensions must be
given

1) When both dimensions are available globally (either as a macro or as a global constant).

#include <stdio.h>
const int M = 3;
const int N = 3;

void print(int arr[M][N])


{
int i, j;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9

2) When only second dimension is available globally (either as a macro or as a global


constant).

#include <stdio.h>
const int N = 3;

void print(int arr[][N], int m)


{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < N; j++)
printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9
The above method is fine if second dimension is fixed and is not user specified. The following methods
handle cases when second dimension can also change.

3) If compiler is C99 compatible


From C99, C language supports variable sized arrays to be passed simply by specifying the variable
dimensions (See this for an example run)

// The following program works only if your compiler is C99 compatible.


#include <stdio.h>

// n must be passed before the 2D array


void print(int m, int n, int arr[][n])
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
print(m, n, arr);
return 0;
}
Output on a C99 compatible compiler:
1 2 3 4 5 6 7 8 9
If compiler is not C99 compatible, then we can use one of the following methods to pass a variable
sized 2D array.

4) Using a single pointer


In this method, we must typecast the 2D array when passing to function.

#include <stdio.h>
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"


print((int *)arr, m, n);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9

You might also like