views:

96

answers:

3

Given: (In C++)

int main () {

    int* ptr;
    int ary [10][2];
    ptr = ary; 

    return 0;
}

How would I access ary[0][1] with ptr?

+1  A: 
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; 

}

James Curran
+3  A: 

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;
}
KennyTM
I am coming from python... this explains my lack of understanding of pointers. The second concept is intriguing but seems like more work than is necessary - just goes to prove how much there is to learn in programing and how many ways there are to do everything. thanks!
Wallter
Alternativly, `int* ptr = ary[0]` is fine, too. Though, In theory, you're only allowed to access `ptr[0]` and `ptr[1]` in this case.
sellibitze
If you are really anal, you can do `ptr+2+1` to access `ary[1][1]` and `ptr + 2 + 2 + 1` to access `ary[2][1]` and so on. That this is guaranteed to work in theory probably shows that one shoudn't worry too much (so although in theory `ptr + 3` is different (UB) than `ptr + 2 + 1` (well defined), in practice it's the same anyway) :)
Johannes Schaub - litb
+1  A: 

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;
fschmitt
Wow, I've never thought of images in that fine of detail before. thanks!
Wallter