C语言 为什么我得到:“错误:赋值给数组类型的表达式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41889548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get: "error: assignment to expression with array type"
提问by akitsme
#include <stdio.h>
int main(void) {
int arr[10];
arr = "Hello";
printf("%s",arr);
return 0;
}
The above code shows compiler error:
上面的代码显示编译器错误:
t.c: In function ‘main':
t.c:5:9: error: assignment to expression with array type
arr = "Hello";
^
t.c:6:12: warning: format ‘%s' expects argument of type ‘char *', but argument 2 has type ‘int *' [-Wformat=]
printf("%s",arr);
^
Whereas the below code works fine.
而下面的代码工作正常。
#include <stdio.h>
int main(void) {
char arr[10] = "Hello";
printf("%s",arr);
return 0;
}
Both look identical to me. What am I missing here?
两者在我看来都一样。我在这里缺少什么?
回答by Sourav Ghosh
They are notidentical.
它们并不相同。
First of all, it makes zero sense to initialize an intarray with a string literal, and in worst case, it may invoke undefined behavior, as pointer to integer conversion and the validity of the converted result thereafter is highly platform-specific behaviour. In this regard, both the snippets are invalid.
首先,int使用字符串字面量初始化数组是零意义的,在最坏的情况下,它可能会调用未定义的行为,因为指向整数转换的指针以及此后转换结果的有效性是高度特定于平台的行为。在这方面,两个片段都是无效的。
Then, correcting the data type, considering the chararray is used,
然后,更正数据类型,考虑使用char数组,
In the first case,
arr = "Hello";is an assignment, which is not allowed with with an array type as LHS of assignment.
OTOH,
char arr[10] = "Hello";is an initializationstatement, which is perfectly valid statement.
回答by akitsme
Don't know how your second code is working (its not working in my case PLEASE TELL ME WHAT CAN BE THE REASON) it is saying: array of inappropriate type (int) initialized with string constant
不知道你的第二个代码是如何工作的(它在我的情况下不起作用,请告诉我可能是什么原因)它说: array of inappropriate type (int) initialized with string constant
Since you can't just assign a whole stringto a integervariable.
but you can assign a single characterto a intvariable like:
int a[5]={'a','b','c','d','d'}
因为你不能只是将一个整体分配string给一个integer变量。但你可以指定一个单一character的int像变量:
int a[5]={'a','b','c','d','d'}

