我知道如果我定义一个像这样的数组
int a [10];
我可以使用指针表示法,使用 a+<corresponding_item_in_array>
访问它的地址
并且它的使用值(value),*(a+<corresponding_item_in_array>)
.
现在我想扭转局面,我用了malloc
为整数指针分配内存,并尝试用下标表示法表示指针但没有成功
int *output_array;
output_array = (int *) (malloc(2*2*2*sizeof(int))); //i.e, space for 3d array
output_array[0][0][1] = 25;
// ^ produces error: subscripted value is neither array nor pointer
我可能已经使用了使用存储映射的指针表达式,但是没有更简单的方法可用吗?为什么?
最佳答案
int*
类型不是 3D 数组类型;它等效于一维数组类型:
int *output_array;
output_array = (int *) (malloc(8*sizeof(int))); //i.e, space for array of 8 ints
output_array[5] = 25; // This will work
更高阶数组的问题在于,为了索引到 2D、3D 等数组,编译器必须知道除第一个维度之外的每个维度的大小,以便正确计算索引的偏移量。要处理 3D 数组,请定义一个 2D 元素,如下所示:
typedef int element2d[2][2];
现在你可以这样做了:
element2d *output_array;
output_array = (element2d*) (malloc(2*sizeof(element2d)));
output_array[0][0][1] = 25; // This will work now
关于c - 等价于数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15126070/