C语言中char数组的成员的默认值是什么? [英] What is the default value of members of a char array in C?

查看:1539
本文介绍了C语言中char数组的成员的默认值是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建一个 char 数组,并且我认为char数组为空。如果我检查数组中第一个元素的值( arr [0] ),则此表达式的结果是什么?

Say I create a char array, and I assume the char array is empty. If I check the value of the first element in the array (arr[0]), what would be the result of this expression?

推荐答案

这取决于声明数组的位置和方式。

It depends on where and how the array is declared.

如果数组是在文件范围内声明的(在任何函数之外),或者声明为 static ,并且没有显式的初始化程序,则数组的内容将为初始化为0。

If the array is declared at file scope (outside of any function), or is declared static, and does not have an explicit initializer, then the contents of the array will be initialized to 0.

如果数组是在块作用域(在函数或块内)声明的,并且未声明为 static ,并且没有显式的初始化程序,则数组的内容是不确定的(本质上是垃圾值,其中一些可能是陷阱表示)。

If the array is declared at block scope (within a function or block) and is not declared static, and does not have an explicit initializer, then the contents of the array are indeterminate (essentially, garbage values, some of which may be trap representations).

如果数组已被显式初始化,则它包含初始化程序中的所有内容。

If the array has been explicitly initialized, then it contains whatever was in the initializer.

编辑

对于以下评论,请注意, •依赖于隐式初始化进行块范围变量。如果需要在创建时将块范围数组清零,请使用初始化程序:

In response to the comments below, note that you shouldn't rely on implicit initialization for block-scope variables. If you need a block-scope array to be zeroed out on creation, use an initializer:

char foo[N] = {0};

当初始化器中的元素少于数组中的元素时,数组中的元素对应于初始化程序中的元素将设置为指定的值;所有剩余的条目都将被隐式初始化,就像声明为 static 一样。

When there are fewer elements in the initializer than there are in the array, elements in the array corresponding to elements in the initializer will be set to the value specified; all remaining entries will be implicitly initialized as if they were declared static.

在上面的示例中,这意味着 foo 的第一个元素显式设置为 0 ,而所有其余元素隐式设置为 0

In the example above, this means that the first element of foo is explicitly set to 0, while all the remaining elements are implicitly set to 0.

这篇关于C语言中char数组的成员的默认值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆