Loading....
Coupon Accepted Successfully!

 

Pointers And Two-Dimensional Arrays

A matrix can represent the two-dimensional elements of an array. In order to display the elements of the two-dimensional array using pointers, it is essential to have ‘&’ operator as a prefix with the array name followed by element numbers.
 

12.13 Write a program to display array elements and their addresses using pointers.

#include<iostream.h>

#include<stdio.h>

#include<conio.h>

void main()

{

clrscr();

int i,j=1,*p;

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

cout<<“\n\tElements of an array with their addresses”;

p=&a[0][0];

cout<<“\n”;

for (i=0;i<9;i++,j++)

{

cout<<“ ”<<*(p)<<“ ”<<unsigned(p);

if (j==3)

{

cout<<“\n”;

j=0;

}

p++;

}

}

OUTPUT
Elements of an array with their addresses
1 65506  2 65508  3 65510
4 65512  5 65514  6 65516
7 65518  8 65520  9 65522

Explanation
In the above program, the two-dimensional array is declared and initialized. The base address of the array is assigned to integer pointer ‘p’. While assigning the base address of the two-dimensional array, the ‘&’ operator is pre-fixed with the array name followed by the element numbers; otherwise, the compiler shows an error. The statement p = &a[0][0] is used in this context. The pointer ‘p’ is printed and incremented in the for loop till it prints the entire array of elements. The if statement splits a line when three elements in each row are printed.





Test Your Skills Now!
Take a Quiz now
Reviewer Name