C中的字符数组声明和初始化 [英] Char array declaration and initialization in C
问题描述
我很好奇为什么在 C 中不允许这样做:
I was curious about why this is not allowed in C:
char myarray[4];
myarray = "abc";
这是允许的:
char myarray[4] = "abc";
我知道在第一种情况下我应该使用 strcpy:
I know that in the first case I should use strcpy:
char myarray[4];
strcpy(myarray, "abc");
但是为什么不允许声明和随后的初始化,而允许声明和同时初始化呢?和C程序的内存映射有关系吗?
But why declaration and later initialization is not allowed and declaration and simultaneous initialization is allowed? Does it relate to memory mapping of C programs?
谢谢!
推荐答案
那是因为你的第一个代码片段没有执行初始化,而是赋值:
That's because your first code snippet is not performing initialization, but assignment:
char myarray[4] = "abc"; // Initialization.
myarray = "abc"; // Assignment.
并且数组在 C 中不能直接赋值.
And arrays are not directly assignable in C.
myarray
这个名字实际上解析为它的第一个元素的地址(&myarray[0]
),它不是一个左值,因此不能成为作业的目标.
The name myarray
actually resolves to the address of its first element (&myarray[0]
), which is not an lvalue, and as such cannot be the target of an assignment.
这篇关于C中的字符数组声明和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!