0
char a1[30]={'h','e'}

will the above array a1 have null character in the 2nd index even though i haven not placed it.

char a2[30]={'h','e','\0'}

when printing,a1 and a2 show same output, hence I think a1 will have null character in the 2nd index.But i am not sure.

2 Answers2

3

Syntax error will be there. If you fix it, yes, h[2] and further elements will be initialized with zeroes.

Array initialization Initialization from brace-enclosed lists

When an array is initialized with a brace-enclosed list of initializers, the first initializer in the list initializes the array element at index zero (unless a designator is specified) (since C99), and each subsequent initializer without a designator (since C99)initializes the array element at index one greater than the one initialized by the previous initializer.

int x[] = {1,2,3}; // x has type int[3] and holds 1,2,3
int y[5] = {1,2,3}; // y has type int[5] and holds 1,2,3,0,0
int z[3] = {0}; // z has type int[3] and holds all zeroes
273K
  • 29,503
  • 10
  • 41
  • 64
1

The compiler has initialized the rest of the 28 bytes of a1 with 0. Hence both a1 and a2 have same output.

AhmadH
  • 76
  • 6
  • with 0 or with \0 since it is character array? – bored_coffee Mar 20 '20 at 17:12
  • some compilers initializes the rest of the values to 0 and some not. – cppiscute Mar 20 '20 at 17:53
  • @spandanBanerjee `\0` is just `0` in octal format. They are the same numeric value. So yes, assigning a numeric 0 to a `char` makes it a null character. – Remy Lebeau Mar 20 '20 at 18:07
  • @gocjack if an array has a fixed size, and is not explicitly initialized with that many values, then the rest of the of values MUST be initialized to 0. The standard dictates that. If a compiler is not doing that, then it is not conforming to the standard – Remy Lebeau Mar 20 '20 at 18:07