0

If I have a C string initialization like this:

char a[5]={'a','b','c'};

Is this valid? What's the value of a[3] and a[4]? Is the null character automatically attached to the end of a?

Thanks!

user1050165
  • 141
  • 1
  • 7
  • The last two elements should be indeterminate or uninitialized IMO. – Morten Jensen Feb 27 '14 at 23:35
  • 1
    _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._ 6.7.8 Initialization 21 – BLUEPIXY Feb 28 '14 at 00:20

4 Answers4

5

They would be initialized to a value of 0. Null is automatically added when you leave some elements uninitialized.

user376507
  • 2,004
  • 1
  • 19
  • 31
0

It depends on what C std you are following:

  • If you follow C90 STRICTLY then it forbids you to do it, Thanks BLUEPIXY for the enlightenment

  • Then, there are certain extensions to these standards which enable you to compile this code without any error, in which case, this is fine.

So, in case of the later, C language takes care by initializing rest to zero .

char a[5] = {}

initializes all indexes to zero.

brokenfoot
  • 11,083
  • 10
  • 59
  • 80
0

If called within a function a[3] and a[4] will be uninitiallised. That is to say, they will be whatever happens to be sitting in memory at the time.

If declared outside a function, a[3] and a[4] will be set to 0.

DXsmiley
  • 529
  • 5
  • 17
-1

Depending on the implementation I believe that the last elements of an array will be either completely random or just equivalents of 0's or even something else, but besides of that array will get initialized just fine.

Peter Nimroot
  • 545
  • 5
  • 14