在C中初始化char数组
Initialize char array in C
我不确定按以下方式初始化后char数组中会有什么:
char buf[5]={0,};
是否等同于
char buf[5]={0,0,0,0,0};
是的,是一样的。如果 initializers 的数量少于数组中的元素,则剩余的元素将被初始化,就像具有静态存储持续时间的对象一样(即 0
) .
所以,
char buf[5]={0,};
等同于
char buf[5]={0,0,0,0,0};
相关阅读:来自 C11
标准文档,第 6.7.9 章,初始化,
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.
是的。
char buf[5]={0,}; // Rest will be initialized to 0 by default
等同于
char buf[5]={0,0,0,0,0};
如果初始值设定项比数组长度短,则该数组的剩余元素被隐式赋予值 0
。
您还应注意,{0,}
(尾随逗号使数组更易于修改)等效于 {0}
作为初始化列表。
是的,当您将数组中的一个元素初始化为 0
时,其余元素将设置为 0
char buf[5] = {0};
char buf[5] = "";
两者相同
是的,两者的结果是一样的。
相关问题少,讨论多here, and a possible duplicated question here。
我不确定按以下方式初始化后char数组中会有什么:
char buf[5]={0,};
是否等同于
char buf[5]={0,0,0,0,0};
是的,是一样的。如果 initializers 的数量少于数组中的元素,则剩余的元素将被初始化,就像具有静态存储持续时间的对象一样(即 0
) .
所以,
char buf[5]={0,};
等同于
char buf[5]={0,0,0,0,0};
相关阅读:来自 C11
标准文档,第 6.7.9 章,初始化,
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.
是的。
char buf[5]={0,}; // Rest will be initialized to 0 by default
等同于
char buf[5]={0,0,0,0,0};
如果初始值设定项比数组长度短,则该数组的剩余元素被隐式赋予值 0
。
您还应注意,{0,}
(尾随逗号使数组更易于修改)等效于 {0}
作为初始化列表。
是的,当您将数组中的一个元素初始化为 0
时,其余元素将设置为 0
char buf[5] = {0};
char buf[5] = "";
两者相同
是的,两者的结果是一样的。
相关问题少,讨论多here, and a possible duplicated question here。