Why do I get: "error: assignment to expression with array type"
Why do I get: "error: assignment to expression with array type"
#include <stdio.h>
int main(void) {
int arr[10];
arr = "Hello";
printf("%s",arr);
return 0;
}
以上代码显示编译错误:
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);
^
而下面的代码工作正常。
#include <stdio.h>
int main(void) {
char arr[10] = "Hello";
printf("%s",arr);
return 0;
}
两者在我看来一模一样。我在这里错过了什么?
它们不相同。
首先,用字符串文字初始化int
数组是零意义的,在最坏的情况下,它可能会调用undefined behavior,作为指向整数转换的指针和此后的转换结果是高度 platform-specific 行为。在这方面,两个片段都是无效的。
然后,修正数据类型,考虑到使用了char
数组,
第一种情况,
arr = "Hello";
是一个 assignment,不允许将数组类型作为赋值的 LHS。
OTOH,
char arr[10] = "Hello";
是一个initialization语句,这是完全有效的语句。
不知道你的第二个代码是如何工作的(它在我的情况下不起作用请告诉我可能是什么原因)它说:array of inappropriate type (int) initialized with string constant
因为您不能将整个 string
分配给 integer
变量。
但您可以将单个 character
分配给 int
变量,例如:
int a[5]={'a','b','c','d','d'}
#include <stdio.h>
int main(void) {
int arr[10];
arr = "Hello";
printf("%s",arr);
return 0;
}
以上代码显示编译错误:
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);
^
而下面的代码工作正常。
#include <stdio.h>
int main(void) {
char arr[10] = "Hello";
printf("%s",arr);
return 0;
}
两者在我看来一模一样。我在这里错过了什么?
它们不相同。
首先,用字符串文字初始化int
数组是零意义的,在最坏的情况下,它可能会调用undefined behavior,作为指向整数转换的指针和此后的转换结果是高度 platform-specific 行为。在这方面,两个片段都是无效的。
然后,修正数据类型,考虑到使用了char
数组,
第一种情况,
arr = "Hello";
是一个 assignment,不允许将数组类型作为赋值的 LHS。
OTOH,
char arr[10] = "Hello";
是一个initialization语句,这是完全有效的语句。
不知道你的第二个代码是如何工作的(它在我的情况下不起作用请告诉我可能是什么原因)它说:array of inappropriate type (int) initialized with string constant
因为您不能将整个 string
分配给 integer
变量。
但您可以将单个 character
分配给 int
变量,例如:
int a[5]={'a','b','c','d','d'}