c - 等价于数组的指针

标签 c arrays pointers

我知道如果我定义一个像这样的数组

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

Demo on ideone.

关于c - 等价于数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15126070/

相关文章:

C 结构和数组

c++ - 无法在 C++ 中初始化指针数组

c - 如何在 opengl/SDL 中使用 ARGB 颜色?

c++ - 如何为unicode字符制作小写字母

c - 从 char 数组中删除一个元素 (C)

c++ - 带指针的基本整数交换

c - c中的数组名到底是什么?

c - g_print 的奇怪输出

c - 为什么我们使用两个间接运算符来访问字符串数组

comparison - 测试 Postgresql 数组字段是空还是空的正确方法是什么