1

我知道如果我定义一个像

int a [10];

我可以使用指针表示法来访问它的地址 usinga+<corresponding_item_in_array> 和它的值 using, *(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

我可能使用了存储映射的指针表达式,但不是更简单的方法可用吗?为什么?

4

3 回答 3

3

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

ideone 上的演示。

于 2013-02-28T02:00:03.663 回答
1

是什么类型的output_arrayint *.

*(output_array+n)or的类型是output[n]什么?int.

是否允许下标int?两个下标(例如*(output_array+n)output[n])都是指针操作,而int不是指针。这解释了您收到的错误。

您可以像这样声明指向 int[x][y] 的指针:int (*array)[x][y];

您可以分配适合替代 3D 数组的存储以array使用:array = malloc(42 * x * y);. 这相当于int array[42][x][y];,除了数组不是可修改的左值,alignof、sizeof 和 address-of 运算符的工作方式不同并且存储持续时间不同。

于 2013-02-28T02:13:56.553 回答
0

因为编译器不知道每个维度的大小,所以它无法找出output_array[0][0][1]应该在哪里。

你可以试试这个

typedef int (* array3d)[2][2];
array3d output_array;
output_array = (array3d) malloc(2 * 2 * 2 * sizeof(int));
output_array[0][0][1] = 25;
printf("%d\n", output_array[0][0][1]);
于 2013-02-28T02:01:45.037 回答