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

initializing string to null termination in order to avoid memset

我写了这段代码:

#include<stdio.h>

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

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

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

来自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;

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

如果您只想将一个字符设置为零(在您的情况下是第一个),您需要将零分配给该字符。

void foo()
{
    char c[64];
    c[0] = 0;
    /* ... */
}