Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, is array initialization with only one element treated specially?

Tags:

arrays

c

While reading this question I wanted to test the input in GCC to see what errors would be output. To my surprise the following line:

char array[] = {"s"};

compiles without error or warning, resulting in an array of size 2 containing "s\0". I would have expected a compiler error because the right side of the expression is of type char*[].

Is an array initialization with only one element not treated as an array in this case, and why?

like image 794
Antoine Avatar asked Nov 09 '11 06:11

Antoine


1 Answers

char array[] = {"s"};

is same as:

char array[] = "s";

Here { } are optional in this case because "s" is string literal.

Or,

char array[] = {'s', '\0'};

In this case, { } are necessary to initialize the array.

like image 173
cpx Avatar answered Oct 19 '22 16:10

cpx