Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize char array in C

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};
like image 948
Ren Avatar asked May 04 '15 14:05

Ren


People also ask

How do you initialize a char array?

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)

How do you initialize an array in C char name?

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.

How do you initiate initialize an array in C?

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];

How a character array is declared and initialized in C?

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.


2 Answers

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.

like image 130
Sourav Ghosh Avatar answered Oct 14 '22 17:10

Sourav Ghosh


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

like image 39
Gopi Avatar answered Oct 14 '22 16:10

Gopi