Simple C string initialization concept clarification needed

简单的C字符串初始化概念需要澄清

问题 (Question)

If I have a C string initialization like this:

char a[5]={'a','b','c'};

Is this valid? What's the value of a[3] and a[4]? Is the null character automatically attached to the end of a?

Thanks!

如果我有一个这样的C字符串初始化:

char a[5]={'a','b','c'};

这是有效的吗?有什么价值[3]和[4]?是null字符自动附加到年底吗?

谢谢!

最佳答案 (Best Answer)

They would be initialized to a value of 0. Null is automatically added when you leave some elements uninitialized.

他们将被初始化的值为0。空你离开时自动添加一些元素未初始化。

答案 (Answer) 2

Depending on the implementation I believe that the last elements of an array will be either completely random or just equivalents of 0's or even something else, but besides of that array will get initialized just fine.

根据实现我相信最后一个数组的元素将完全随机的或只是相当于0或者别的东西,但除了数组初始化。

答案 (Answer) 3

It depends on what C std you are following:

  • If you follow C90 STRICTLY then it forbids you to do it, Thanks BLUEPIXY for the enlightenment

  • Then, there are certain extensions to these standards which enable you to compile this code without any error, in which case, this is fine.

So, in case of the later, C language takes care by initializing rest to zero .

char a[5] = {}

initializes all indexes to zero.

这取决于C性病你:

  • 如果你遵循C90严格禁止你做它,感谢BLUEPIXY启蒙运动

  • 然后,有一些扩展这些标准允许您编译这个代码没有任何错误,在这种情况下,这是很好。

所以,在以后,C语言负责初始化其他为零。

char a[5] = {}

答案 (Answer) 4

If called within a function a[3] and a[4] will be uninitiallised. That is to say, they will be whatever happens to be sitting in memory at the time.

If declared outside a function, a[3] and a[4] will be set to 0.

如果在一个函数[3]和[4]将uninitiallised。也就是说,他们会不管发生什么事,在内存中。

如果外声明一个函数,一个[3]和[4]将被设置为0。

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/22083010