开发者

C++: how to access a multidimensional array with pointers?

开发者 https://www.devze.com 2023-01-17 17:18 出处:网络
Given: 开发者_如何学Go(In C++) int main () { int* ptr; int ary [10][2]; ptr = ary; return 0; } How would I access ary[0][1] with ptr?You can\'t, because the type of ptr is wrong. The variable sh

Given: 开发者_如何学Go(In C++)

int main () {

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

    return 0;
}

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


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;
}


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; 

}


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;


it is possible, just look at this example ( these are dynamic arrays, but works with static too ):

void bla ( void )
{
    const int32_t sx = 50, sy = 30, sz = 50;
    uint64_t *** n = NULL;
    n = ( uint64_t*** )malloc( sizeof( uint64_t** ) * sx );
    for ( int32_t x = 0; x < sx; x++ )
    {
        *( n + x ) = ( uint64_t** )malloc( sizeof( uint64_t* ) * sy );
        for ( int32_t y = 0; y < sy; y++ )
            *( *( n + x ) + y ) = ( uint64_t* )malloc( sizeof( uint64_t ) * sz );
    }

    for ( int32_t x = 0; x < sx; x++ )
        for( int32_t y = 0; y < sy; y++ )
            for( int32_t z = 0; z < sz; z++ )
                *( *( *( n + x ) + y ) + z ) = 1024 * 1024;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消