Hi Im just starting to get my head around pointers and arrays and Ive more or less know how to manipulate pointers in a one dimensional arrays to display the elements. But how about in multidimensional arrays? I have been practicing with this code:
#include<iostream>
using namespace std;
int main()
{
int a[2][3]= { {1,2,3},{4,5,6}};
int (*ptr)[3] = &a[0]; // or (*ptr)[3] = a;
cout <<"Adress 0,0: "<< a << endl;
cout <<"Adress 0,0: "<< ptr << endl;
cout <<"Value 0,0: "<< *a[0] << endl;
cout <<"Value 0,0: "<< *(ptr)[0]<< endl;
cout <<"Adress 0,1: "<< &a[0][1] << endl;
cout <<"Adress 0,1: "<< (ptr)[1] << endl;
return 0;
}
I have managed to display the address and value of a[0][0] using the array name and the pointer, but how to display the address and value of a[0][1] and the succeeding elements by using the pointer?
(ptr)[1]
(same as ptr[1]
) doesn't point to a[0][1]
, it points to a[1][0]
because you defined ptr
as a pointer to int[3]
, not int
. Therefore incrementing ptr
by 1
with ptr[1]
skips three int
s, up to a[1][0]
.
To increment ptr
by the size of one int
instead of three int
s:
ptr[0] + 1
The above will point to a[0][1]
. And to access that:
*(ptr[0] + 1)
#include<iostream>
using namespace std;
int main()
{
int a[2][3]= { {1,2,3},{4,5,6} };
int (*ptr)[3] = &a[0]; // or (*ptr)[3] = a;
cout <<"Adress 0,0: "<< a << endl;
cout <<"Adress 0,0: "<< ptr << endl;
cout <<"Value 0,0: "<< *a[0] << endl;
cout <<"Value 0,0: "<< *((ptr)[0]+0)<< endl;
cout <<"Adress 0,1: "<< &a[0][1] << endl;
cout <<"Adress 0,1: "<< (ptr)[0]+1 << endl;
cout <<"value 0,1: "<< a[0][1] << endl;
cout <<"value 0,1: "<< *((ptr)[0]+1) << endl;
cout <<"Adress 1,0: "<< &a[1][0] << endl;
cout <<"Adress 1,0: "<< (ptr)[1] << endl;
cout <<"value 1,0: "<< a[1][0] << endl;
cout <<"value 1,0: "<< *((ptr)[1]+0) << endl;
return 0;
}
Hope this clears your doubt.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.