Given: (In C++)
int main () {
int* ptr;
int ary [10][2];
ptr = ary;
return 0;
}
How would I access ary[0][1]
with ptr
?
Given: (In C++)
int main () {
int* ptr;
int ary [10][2];
ptr = ary;
return 0;
}
How would I access ary[0][1]
with ptr
?
typedef int tenints[10]; // tenints is an array of 10 ints
int main () {
tenints ary[2]; // array of 2 tenints, same as your int ary[10][2];
tenints* ptr = ary
// ptr[0] or *ptr is the first row
// ptr[1] or *(ptr+1)is the second row
int* ptr2 = ptr[0];
// ptr2[1] or *(ptr2+1) is ary[0][1]
// if you don't want do use as intermediate variable,
// just substitute "*ptr" for "ptr2" in "*(ptr2+1)"
int val = *((*ptr)+1);
return 0;
}
You can't, because the type of ptr
is wrong. The variable should be declared as int(*)[2]
(pointer to an array of size 2 of integers). Then you could just use ptr[0][1]
.
#include <cstdio>
int main () {
int (* ptr) [2]; // <--
int ary [10][2];
ptr = ary;
ary[0][1] = 5;
printf("%d\n", ptr[0][1]);
return 0;
}
If you must use an int*
, you need to introduce a reinterpret_cast
. The array indices are laid out like:
0 1 2 3 2*n 2*n+1
[0][0] [0][1] [1][0] [1][1] ... [n][0] [n][1]
so you could use ptr[1]
to get ary[0][1]
.
#include <cstdio>
int main () {
int* ptr;
int ary [10][2];
ptr = reinterpret_cast<int*>(ary); // <--
ary[0][1] = 5;
printf("%d\n", ptr[1]);
return 0;
}
What you want only works when the data is on block which it might not be in all cases. In the context of image processing, you mostly do something like this:
int width = 1024;
int height = 768;
char* img = new char[width*height];
char** img2d = new char*[height];
for (int y = 0; y < height; ++y){
img2d[y] = img + y*width;
}
//set pixel at x=50, y=100
img2d[100][50] = 1;
//does the same
img2d[100*width+50] = 1;
delete[] img;