我知道这个问题之前已经被问过,但我无法完全缩小我在这里做错的范围
int* arr[2];
arr = (int (*)[2]) malloc(sizeof(int) * size);
为什么 Visual Studio 告诉我表达式必须是可修改的左值?我正在尝试创建一个具有恒定列大小的数组,因为它始终是两个,但行会有所不同。
最佳答案
arr
是一个指针数组。一旦初始化,您就无法为其分配任何内容。由于您试图将其值设置为调用 malloc
的返回值,因此您可能希望它是一个指向数组的指针。在这种情况下,请使用:
int (*arr)[2];
此外,不要转换 malloc
的返回值。请参阅Do I cast the result of malloc? .
使用
int (*arr)[2];
arr = malloc(sizeof(*arr) * size);
// ^^^^^^^^^^^^ We are speculating this is what you need,
// not sizeof(int)
如果您希望 arr
指向 15 x 2
对象的数组,则需要使用:
arr = malloc(sizeof(*arr) * 15);
关于c - malloc 时表达式必须是可修改的左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165077/