难道一个字符串算作一个局部的初始化和零初始化? [英] Does a string literal count as a partial initializer and zero-initialize?

查看:109
本文介绍了难道一个字符串算作一个局部的初始化和零初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,你可以的部分初始化的结构或阵列,其结果是未在初始化中提到的成员/元素是零初始化。 (C99部分6.7.8.19)。例如: -

  int类型的[4] = {1,2};
//一个[0] == 1
//一个[1] == 2
// A [2] == 0
// A [3] == 0

您也可以初始化字符串常量(C99部分6.7.8.14),和字符类型的数组,连续的字符...初始化数组的元素。例如: -

 字符B〔4] =ABC;
// B [0] =='一'
// B [1] =='B'
// B [2] =='c'的
// B [3] =='\\ 0'

所有pretty简单。但是,如果你明确地给数组的长度,而是用文字说太矮了,填补了数组会发生什么?是剩余的字符初始化为零,或者他们有未定义值?

 字符C [4] =A;
// C [0] =='一'
// C [1] =='\\ 0'
// C [2] ==?
// C [3] ==?

把它当作一个部分初始化将使意义,它将使字符C [4] =一个完全一样字符C [ 4] = {'A​​'} ,它会选择让你简明字符D [N]零初始化整个字符数组的有用的副作用= ,但它并不完全清楚,我认为这就是规范要求。


解决方案

 字符C [4] =A;

在阵列中的所有剩余的元素将被设置为 0 。也就是说,不仅 C [1] C [2] C [ 3]

请注意,这不依赖于的ç存储时间,我。即,即使 C 具有自动存储时间剩余的元素将被设置为 0

从C标准(重点煤矿):


  

(C99,6.7.8p21)如果有一个大括号括起来的列表更少的初始化值多于元件或部件的集合体,或更少的字符的字符串用于初始化已知大小比有数组中元素的数组,则总的的其余部分应被初始化隐含一样具有静态存储持续时间的对象。


In C, you can partially initialize a struct or array, with the result that the members/elements that aren't mentioned in the initializer are zero-initialized. (C99 section 6.7.8.19). For example:-

int a[4] = {1, 2};
// a[0] == 1
// a[1] == 2
// a[2] == 0
// a[3] == 0

You can also initialize "an array of character type" with a string literal (C99 section 6.7.8.14), and "successive characters ... initialize the elements of the array". For example:-

char b[4] = "abc";
// b[0] == 'a'
// b[1] == 'b'
// b[2] == 'c'
// b[3] == '\0'

All pretty straightforward. But what happens if you explicitly give the length of the array, but use a literal that's too short to fill the array? Are the remaining characters zero-initialized, or do they have undefined values?

char c[4] = "a";
// c[0] == 'a'
// c[1] == '\0'
// c[2] == ?
// c[3] == ?

Treating it as a partial initializer would make sense, it would make char c[4] = "a" behave exactly like char c[4] = {'a'}, and it would have the useful side-effect of letting you zero-initialize a whole character array concisely with char d[N] = "", but it's not at all clear to me that that's what the spec requires.

解决方案

 char c[4] = "a";

All the remaining elements of the array will be set to 0. That is, not only c[1] but also c[2] and c[3].

Note that this does not depend on the storage duration of c, i. e., even if c has automatic storage duration the remaining elements will be set to 0.

From the C Standard (emphasis mine):

(C99, 6.7.8p21) "If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration."

这篇关于难道一个字符串算作一个局部的初始化和零初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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