如何仅使用指针访问结构内的二维数组

How to access a 2d array inside a struct using only pointers

作为 C 初学者尝试理解指针- 我有这个结构:

    typedef struct {
        int size;           // dimension of array
        int **arr; // pointer to heap allocated array
    } someStruct;

所以我使用 malloc 生成这个结构和一个数组,并将所有值初始化为零-

someStruct *m = (someStruct*)malloc(sizeof(someStruct));
m->size = n;
m->arr = (int**)malloc(n * sizeof(int));
// initialize array
for (int i = 0; i < n; i++) {
    *(m->arr + i) = (int*)malloc(n * sizeof(int));
    // set value to 0
    for (int j = 0; j < n; j++) {
        *(*(m->arr + i) + j) = 0;
    }
}

在此之后我基本上继续使用相同类型的指针逻辑在后期访问数组-

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        int num =  *(*(m->arr + i) + j);
        printf("num: %d\n", num);
    }
}

这是问题所在 - 当我尝试使用这种访​​问方法时,我显然没有得到正确的答案 - 我的打印输出如下所示:

num: -2043774080
num: 22031
num: 0
num: 0
...
num: 0
num: 0

这是真正奇怪的部分 - 'weird' 随机数的这个看似错误仅在我创建和访问大小为 5-

的数组时才会出现

我开始相信整个

*(*(m->arr + i) + j)

访问方法一定是错误的 - 对此的任何帮助都会非常有用。在此先感谢,如果已经回答,我深表歉意,我的搜索无法找到它。

你应该给出完整的代码,但我想我能够弄清楚你的意图。你有一个明显的问题,还有很多风格问题。我认为您的代码应该如下所示:

typedef struct {
    int size;           // dimension of array
    int **arr; // pointer to heap allocated array
} MagicSquare;

  :
  :

// no need to dynamically allocate this, it is small
MagicSquare m;
m.size = n;
m.arr = malloc(n * sizeof(int*));  // note it is sizeof(int*), not (int)

// initialize array
for (int i = 0; i < n; i++) {
    m.arr[i] = malloc(n * sizeof(int));
    // set value to 0
    for (int j = 0; j < n; j++) {
        m.arr[i][j] = 0;
    }
}

  :
  :

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        printf("num: %d\n", m.arr[i][j]);
    }
}

请注意,如果您想将分配的内存初始化为零,您应该只使用 calloc,它会为您完成此初始化:

// initialize array
for (int i = 0; i < n; i++) {
    m.arr[i] = calloc(n,sizeof(int));
}