Search code examples
carraysinitializationc-strings

initializing string to null termination in order to avoid memset


I wrote this code:

#include<stdio.h>

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

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

In the line //Q is it the entire string set to '\0' or just the 0th index? Though on checking the output it prints hello but I am not sure if its some value by fallacy or by design?


Solution

  • From the C Standard (6.7.9 Initialization)

    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.

    and

    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;

    Thus all elements of the character array will be zero-initialized.