I am not sure what will be in the char array after initialization in the following way:
char buf[5]={0,};
Is that equivalent to
char buf[5]={0,0,0,0,0};
You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)
Initializing array with a string (Method 1):char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a '\0' (null) byte. The null byte is required as a terminating byte when string is read as a whole.
Array Initialization Using a Loop The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C. // declare an array. int my_array[5];
Use {} Curly Braced List Notation to Initialize a char Array in C. A char array is mostly declared as a fixed-sized structure and often initialized immediately. Curly braced list notation is one of the available methods to initialize the char array with constant values.
Yes, it is the same. If there are less number of initializers than the elements in the array, then the remaining elements will be initialized as if the objects having static storage duration, (i.e., with 0
).
So,
char buf[5]={0,};
is equivalent to
char buf[5]={0,0,0,0,0};
Related Reading : From the C11
standard document, chapter 6.7.9, initalization,
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.
Yes when you initialize one element in the array to 0
the rest are set to 0
char buf[5] = {0};
char buf[5] = "";
Both are same
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With