c - 如何从 C 中作为结构成员的指针访问数组中的值

标签 c pointers multidimensional-array struct

我搜索了 stackoverflow,看到了我问题中的所有单词组合,但没有看到我的问题。

我有一个整数数组,它恰好是一个二维数组。

const int themap[something][something] = { {0, ...

我有一个结构,我想在我的程序中有一个指向这个数组的指针

typedef struct {
int** mymap;
} THE_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

如果我直接使用数组(作为全局变量),则完全相同的功能可以从图片中取出结构

int value;
...
//access the map directly
value = themap[x][y]
//everyone is happy!

我想使用该结构,因为实际上它会携带其他信息,而且我需要能够将指针分配给具有不同数据的其他数组。

最佳答案

您的二维数组与 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];

可以使用 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];

关于c - 如何从 C 中作为结构成员的指针访问数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379653/

相关文章:

c - 给 char 指针赋值

c - 单调路径面积的递归和

c - 结构体中的算术运算

pointers - Golang自定义单链表的误解

c# - 我应该使用列表吗?

c++ - 高性能 C++ 多维数组

c - 在 C 中分配二维数组

objective-c - "&"字符在 obj-c 中附加到 var 是什么意思

c++ - 为我的对象分配特定/明确的内存位置

c - 来自不兼容指针类型警告的初始化。找不到问题