字符数组声明和初始化用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
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?
谢谢!
推荐答案
这是因为你的第一个code段未执行的初始化的,但是的分配的:
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屋!