amm*_*nus 1 c struct pointers multidimensional-array
我搜索了stackoverflow并看到了我的问题中的每个单词组合,但不是我的问题.
我有一个int数组,它恰好是一个2d数组.
const int themap[something][something] = { {0, ...
Run Code Online (Sandbox Code Playgroud)
我有一个结构,我希望在我的程序中有一个指向这个数组的指针
typedef struct {
int** mymap;
} THE_STRUCT
Run Code Online (Sandbox Code Playgroud)
在我的程序中,我想通过struct的指针迭代数组的值,但是如果我尝试通过它访问它,我的数据似乎已损坏.句法
int value;
THE_STRUCT mystruct;
mystruct = (int**) themap;
...
//access the map data from mystruct's pointer?
value = mystruct.mymap[x][y];
//doesn't seem to return correct values
Run Code Online (Sandbox Code Playgroud)
如果我直接使用数组(作为全局变量),那么从图片中取出结构可以使用相同的函数
int value;
...
//access the map directly
value = themap[x][y]
//everyone is happy!
Run Code Online (Sandbox Code Playgroud)
我想使用结构实际上它将携带其他信息以及我需要能够将指针分配给具有不同数据的其他数组的事实.
你的二维数组与a不同int **
.如果你想在其中存储指向它的指针struct
,你可以这样做:
const int themap[something1][something2] = { {0, ...
typedef struct {
const int (*mymap)[something2];
} THE_STRUCT;
...
THE_STRUCT my_struct;
my_struct.mymap = themap;
...
int value = my_struct.mymap[x][y];
Run Code Online (Sandbox Code Playgroud)
它是可以使用的int **
,但它需要一些努力:
const int themap[something1][something2] = { {0, ...
const int * themapPointerArray[something1] = {themap[0], themap[1], ..., themap[something1 - 1]};
typedef struct {
const int **mymap;
} THE_STRUCT;
...
THE_STRUCT my_struct;
my_struct.mymap = themapPointerArray;
...
int value = my_struct.mymap[x][y];
Run Code Online (Sandbox Code Playgroud)