簡體   English   中英

C ++:如何使用指針訪問多維數組?

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

給定:(在C ++中)

int main () {

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

    return 0;
}

如何使用ptr訪問ary[0][1]

您不能,因為ptr的類型是錯誤的。 該變量應聲明為int(*)[2] (指向整數2的數組的指針)。 然后,您可以只使用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;
}

如果必須使用int* ,則需要引入reinterpret_cast 數組索引的布局如下:

    0       1        2         3              2*n      2*n+1
[0][0]  [0][1]   [1][0]    [1][1]    ...    [n][0]    [n][1]

因此您可以使用ptr[1]獲得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; 

}

有可能,只要看一下這個例子(它們是動態數組,但也可以用於靜態數組):

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

您想要的僅在數據處於阻塞狀態時才起作用,而並非在所有情況下都如此。 在圖像處理的上下文中,您通常會執行以下操作:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM