Pointers And Two Dimensional Arrays

C Pointers and Two-Dimensional Arrays

Pointers and two dimensional arrays is a very important concept in C programming language.The understanding between Pointers and Two-Dimensional Arrays is presented here with a simple programming code.Please first refer to the programming code which is given in this page.If you go through the program codes,then it is easy to understand by following the explaination.

Let’s figure out how the program works. The compiler knows that stu is an array containing 5 one-dimensional arrays, each containing 2 integers. Each one-dimensional array occupies 4 bytes (two bytes for each integer). These one-dimensional arrays are placed linearly (zeroth 1-D array followed by first 1-D array, etc.). Hence each one-dimensional arrays starts 4 bytes further along than the last one, as can be seen in the memory map of the array.

We know that the expressions stu[0] and stu[1] would yield the addresses of the zeros and first one-dimensional array respectively. From Figure, these addresses turn out to be 5000 and 5004.
Now, we have been able to reach each one-dimensional array. What remains is to be able to refer to individual elements of a one-dimensional array. Suppose we want to refer to the element stu[2][1] using pointers. We know (from the above program) that stu[2] would give the address 5008, the address of the second one-dimensional array. Obviously ( 5008 + 1 ) would give the address 5010. Or ( stu[2] + 1 ) would give the address 5010. And the value at this address can be obtained by using the value at address operator, saying *( stu[2] + 1).

Similarly, *( stu[2] + 1 ) is same as, *( *( stu + 2 ) + 1 ). Thus, all the following expressions refer to the same element,
stu[2][1] * (stu[2] + 1)
* (*(stu + 2) + 1)

#include<stdio.h>
#include<conio.h>
void main( )
{
int stu[5][2] = {
{ 12,56},
{13, 33},
{ 14,80},
{15, 78}
};
int i;
for (i = 0 ; i <= 3 ; i++ )
printf ("\nAddress of %d th 1-D array = %u", i, stu[i]);
}

And here is the output…
Address of 0 th 1-D array = 5000
Address of 1 th 1 -D array = 5004
Address of 2 th 1-D array = 5008
Address of 3 th 1-D array = 5012

Using these concepts the following program prints out each element of a two-dimensional array using pointer notation.

Pointer notation to access 2-D array elements

#include<stdio.h>
#include<conio.h>

void main()
{
int stu[5][2] = {
{12 56 },
{13, 33},
{ 14,80},
{15, 78}
};
int i, j;
for (i = 0 ; i <= 3 ; i++ )
{
printf ("\n");
for (j = 0 ; j <= 1 ; j++)
printf ("%d ",*(*( stu + i) + j));
}
}

And here is the output…
12 56
13 33
14 80
15 78

Click For The Resources
Click For The Next Resource

This entry was posted in Uncategorized. Bookmark the permalink.