gpt4 book ai didi

c - 将字符串初始化为空终止以避免 memset

转载 作者:行者123 更新时间:2023-12-01 13:10:50 26 4
gpt4 key购买 nike

我写了这段代码:

#include<stdio.h>

int main(void)
{
char c[10]=""; //Q

if(c[2]=='\0')
printf("hello");
return 0;
}

//Q 行中,是将整个字符串设置为 '\0' 还是仅设置为 0th 索引?虽然在检查输出时它会打印 hello 但我不确定它的某些值(value)是出于谬误还是设计?

最佳答案

来自C标准(6.7.9初始化)

21 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.

  1. ...If an object that has static or thread storage duration is not initialized explicitly, then:

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

因此字符数组的所有元素都将被零初始化。

关于c - 将字符串初始化为空终止以避免 memset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60156081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com