#include <stdio.h>
#include <malloc.h>
#define NUM_ROWS 5
#define NUM_COLS 10
void dynamic_allocation_malloc3();
int main() {
dynamic_allocation_malloc3();
}
void dynamic_allocation_malloc3() {
int (**ptr)[]; //ptr is a pointer to a pointer to a 1-d integer array
ptr = malloc(NUM_ROWS * sizeof(int(*)[])); // allocate as many as NUM_ROWS pointers to 1-d int arrays. The memory holds pointers to rows
for(int row=0; row < NUM_ROWS; row++) {
ptr[row] = malloc(NUM_COLS * sizeof(int));
for(int col=0; col < NUM_COLS; col++) {
ptr[row][col] = 17;
}
}
}
此代码在编译时出现以下错误:
$ gcc -std=c99 dynamic_allocation_scratch.c
dynamic_allocation_scratch.c: In function ‘dynamic_allocation_malloc3’:
dynamic_allocation_scratch.c:23:13: error: invalid use of array with unspecified bounds
ptr[row][col] = 17;
^
dynamic_allocation_scratch.c:23:13: error: invalid use of array with unspecified bounds
修复方法是替换
ptr[row][col] = 17;
使用
(*ptr[row])[col] = 17; //de-reference the pointer to 1-d array to get the array and then use col index
问题:
我想在此澄清我的理解。我是否正确地解释了为什么修复是有效的?如果能进一步澄清为什么原始代码不起作用,我们也将不胜感激。
发布于 2019-12-23 07:28:29
你需要决定你想要多少个间接的方向。指向数组的指针有三个级别,但是
ptr[row][col]
只有两个层次。让我们看看
ptr // a pointer to a pointer to an array
ptr[row] // a pointer to an array
ptr[row][col] // an array
ptr[row][col] = 17 // an array equals 17; explain that to your nearest rubber duck
发布于 2019-12-23 08:45:50
ptr[row]
具有指向未知界限的int
数组的类型指针。因此,ptr[row][col]
的意思是“未知界限的col
-th数组”,因为我们不知道每个数组的大小以便在内存中找到下一个数组,因此不能计算这个数组。
第一个*(ptr[row])
是有效的,因为这不涉及任何算术。该表达式具有未知界限的int
类型数组,您可以在这种数组上使用运算符[col]
。
https://stackoverflow.com/questions/59451107
复制相似问题