【问题标题】:How to access value in array from a pointer that is a member of a struct in C如何从作为C中结构成员的指针访问数组中的值
【发布时间】:2012-09-12 00:18:01
【问题描述】:

我搜索了 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!

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

【问题讨论】:

  • 我很惊讶这甚至可以编译。
  • themap 可以被解释为一个指针,并且任何指针-指针转换在C语言中都是合法的。

标签: c pointers multidimensional-array struct


【解决方案1】:

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

【讨论】:

  • 如果我不想在结构中硬编码数组长度 'something2' 怎么办?
  • 那么你应该线性化数组——const int themapLinear[something1 * something2] = {0, ...},这样你只需要存储一个const int *。然后,您可以将themap[x][y] 替换为themapLinear[(x * something2) + y],这里something2 直到运行时才需要知道(并且可以,例如,传递给函数)。
  • 问题在于,如果themap 是一个二维数组,则解释themap[x][y] 之类的内容需要知道每行中有多少个元素。编译器需要在编译时知道这一点。
  • 可以使用int **,我已经相应地更新了我的答案。
  • 啊,很好。 const 告诉编译器您不会修改这些值,并且它可以假设是这种情况。如果您尝试,它会警告您。 种方法可以解决这个问题,但如果您不需要修改存储的数据,声明数组和指向const 数据的指针仍然很好,因为它有助于防止错误并使其更容易处理不同的数据使用相同数组的代码。
【解决方案2】:

多维数组int [][] 和双间接指针int ** 是两个完全不同的东西。

对于 C 来说,多维数组是一个以不同方式索引的一维数组。说xint [3][4]。然后,x 包含 12 个顺序打包的元素,x[1][2] 只是该一维数组的第 6 个元素。

被视为二维数组的双间接指针是指向数组的指针的数组。所以,如果yint **,那么y[1][2] 表示“y 的第二个元素指向的数组的第三个元素”。

因此,您不能在 int [][]int ** 之间进行转换,因为它们只是代表不同的事物(您将 int [][] 转换为 int ** 会导致 int [][] 数组中的整数被视为指针,这将不可避免地崩溃)。

相反,您可以将int [M][N] 转换为int (*)[N]——一个指向N-length 数组的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-01
    • 2021-12-17
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多