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

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

问题描述

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.

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.

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.

EDIT

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};

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.

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天全站免登陆