简体   繁体   English

C中的Char数组声明和初始化

[英]Char array declaration and initialization in C

I was curious about why this is not allowed in C: 我很好奇为什么在C中不允许这样做:

char myarray[4];

myarray = "abc";

And this is allowed: 这是允许的:

char myarray[4] = "abc";

I know that in the first case I should use strcpy : 我知道在第一种情况下我应该使用strcpy

char myarray[4];

strcpy(myarray, "abc");

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? 它与C程序的内存映射有关吗?

Thanks! 谢谢!

That's because your first code snippet is not performing initialization , but assignment : 那是因为你的第一个代码片段没有执行初始化 ,而是分配

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C. 并且数组不能直接在C中分配。

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. 名称myarray实际上解析为其第一个元素( &myarray[0] )的地址,它不是左值 ,因此不能作为赋值的目标。

Yes, this is a kind of inconsistency in the language. 是的,这是语言中的一种不一致。

The "=" in myarray = "abc"; myarray = "abc";的“=” myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; 是赋值(由于数组基本上是一种常量指针,它不起作用),而在char myarray[4] = "abc"; it's an initialization of the array. 这是数组的初始化。 There's no way for "late initialization". “晚期初始化”无法实现。

You should just remember this rule. 你应该记住这个规则。

myarray = "abc";

...is the assignation of a pointer on "abc" to the pointer myarray. ...是指向myarray指针的“abc”指针。

This is NOT filling the myarray buffer with "abc". 这不是用“abc”填充myarray缓冲区。

If you want to fill the myarray buffer manually, without strcpy(), you can use: 如果你想手动填充myarray缓冲区,没有strcpy(),你可以使用:

myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;

or 要么

char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;

Your question is about the difference between a pointer and a buffer (an array). 你的问题是关于指针和缓冲区(数组)之间的区别。 I hope you now understand how C addresses each kind. 我希望你现在明白C如何解决各种问题。

This is another C example of where the same syntax has different meanings (in different places). 这是另一个C示例,其中相同的语法具有不同的含义(在不同的地方)。 While one might be able to argue that the syntax should be different for these two cases, it is what it is. 虽然人们可能会认为这两种情况的语法应该不同,但它就是这样。 The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment"). 这个想法不是说“不允许”,而是第二件事意味着不同的东西(意思是“指针分配”)。

I think these are two really different cases. 我认为这是两个非常不同的案例。 In the first case memory is allocated and initialized in compile-time. 在第一种情况下,在编译时分配和初始化存储器。 In the second - in runtime. 在第二个 - 在运行时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM