在C中将直接字符串分配给char数组
Assigning direct string to char array in C
在二维数组中,直接将字符串赋值给char数组,报错
char name[5][10];
name[0] = "hello";
但是,使用 strcpy
,将字符串复制到 char 数组工作正常。
char name[5][10];
strcpy(name[0],"hello");
为什么第一个案例不起作用?
因为数组类型不是可修改的左值,因此不能是 "assigned"。
赋值运算符需要一个可修改的左值作为 LHS 操作数。
相关,引用 C11
,章节 §6.5.16
An assignment operator shall have a modifiable lvalue as its left operand.
以及第 6.3.2.1 章
[....] A modifiable lvalue is an lvalue that
does not have array type, does not have an incomplete type, does not have a constqualified
type, and if it is a structure or union, does not have any member (including,
recursively, any member or element of all contained aggregates or unions) with a constqualified
type.
在您的例子中,对于定义为
的数组
char name[5][10];
元素name[0]
的类型为char [10]
,即10char
个数组。
因为C不允许赋值给数组。这是语言的限制。
请注意,您 可以 分配给 struct
,即使它 包含 数组:
#include <stdio.h>
struct x
{
char s[20];
};
int main(void)
{
struct x x;
x = (struct x){ "test" };
puts(x.s);
}
在二维数组中,直接将字符串赋值给char数组,报错
char name[5][10];
name[0] = "hello";
但是,使用 strcpy
,将字符串复制到 char 数组工作正常。
char name[5][10];
strcpy(name[0],"hello");
为什么第一个案例不起作用?
因为数组类型不是可修改的左值,因此不能是 "assigned"。
赋值运算符需要一个可修改的左值作为 LHS 操作数。
相关,引用 C11
,章节 §6.5.16
An assignment operator shall have a modifiable lvalue as its left operand.
以及第 6.3.2.1 章
[....] A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a constqualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a constqualified type.
在您的例子中,对于定义为
的数组char name[5][10];
元素name[0]
的类型为char [10]
,即10char
个数组。
因为C不允许赋值给数组。这是语言的限制。
请注意,您 可以 分配给 struct
,即使它 包含 数组:
#include <stdio.h>
struct x
{
char s[20];
};
int main(void)
{
struct x x;
x = (struct x){ "test" };
puts(x.s);
}