![](/img/trans.png)
[英]Why do my integer array elements contain the wrong values when I assign it character values in C and how can I fix this?
[英]Why can't I assign values to the array elements?
在这个 C 程序中:
#include <stdlib.h>
struct mystruct
{};
int
main()
{
struct mystruct* obj = malloc(sizeof(struct mystruct));
struct mystruct(*list)[10];
list[0] = obj;
}
基本上,我正在尝试创建一个固定大小的指针数组(指向某个结构)。
main
的最后一行导致错误“表达式必须是可修改的左值”。 但为什么?
我知道您不允许分配给 arrays,但我不想分配给数组,我想分配给指针。
我正在尝试创建一个固定大小的指针数组
但你不是:你正在创建一个指向固定大小的结构数组的指针。 您可以使用cdecl来帮助您处理复杂类型的语法。
cdecl> explain struct mystruct(*list)[10];
declare list as pointer to array 10 of struct mystruct
cdecl> explain struct mystruct *list[10];
declare list as array 10 of pointer to struct mystruct
来自 GCC 和 Clang 的错误消息比您的编译器更清楚。 考虑使用多个编译器来获得有关您的代码的更多反馈。
% gcc -Wall -O a.c
a.c: In function ‘main’:
a.c:11:11: error: assignment to expression with array type
11 | list[0] = obj;
| ^
$ clang -Wall -O a.c
a.c:11:11: error: array type 'struct mystruct [10]' is not assignable
list[0] = obj;
~~~~~~~ ^
1 error generated.
struct mystruct (*list)[10];
创建list
作为指向struct mystruct
的 10 元素数组的指针。 你想要的是
struct mystruct *list[10];
它将list
创建为指向struct mystruct
的 10 元素指针数组。 这些括号完全改变了含义。 现在你的
list[0] = obj;
声明应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.