1

Is there any null character after the character c in memory:

char a[3]="abc";
printf("the value of the character is %.3s\n",a);
printf("the value of the character is %s\n",a);

Which line is correct ?

Sabrina
  • 1,460
  • 11
  • 23
  • 2
    No there is no NUL in your `a` array as shown. I'm sure this is a dup and am looking for that (I may have even answered it myself). – kaylum Mar 08 '17 at 23:06
  • No, there isn't. – Barmar Mar 08 '17 at 23:06
  • So the compiler only add the null character if the lenght is sufficient right ? – Sabrina Mar 08 '17 at 23:08
  • @yellowantphil sorry just made copy-paste and forgot to remove the precision. – Sabrina Mar 08 '17 at 23:09
  • 3
    Possible duplicate of [C char array initialization](http://stackoverflow.com/questions/18688971/c-char-array-initialization) – kaylum Mar 08 '17 at 23:09
  • One of the answers in the dup quotes the relevant sections of the C spec which answers your question. – kaylum Mar 08 '17 at 23:10
  • the compiler will produce code that always inserts the full literal (4 characters) starting at the location where the array starts. I.E. the array will be overrun. This is undefined behavior and can/will lead to a seg fault event. – user3629249 Mar 10 '17 at 00:30
  • @user3629249 You are incorrect. – zwol Mar 12 '17 at 16:47
  • @kaylum I think this _question_ is sufficiently different from the linked one to warrant its own answer. – zwol Mar 12 '17 at 16:47

1 Answers1

1

char a[3] = "abc"; is well-formed; the three elements of the array will be the characters 'a', 'b', and 'c'. There will not be a NUL terminator. (There might still happen to be a zero byte in memory immediately after the storage allocated to the array, but if there is, it is not part of the array. printf("%s", a) has undefined behavior.)

You might think that this violates the normal rule for when the initializer is too long for the object, C99 6.7.8p2

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

That's a "shall" sentence in a "constraints" section, so a program that violates it is ill-formed. But there is a special case for when you initialize a char array with a string literal: C99 6.7.8p14 reads

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

The parenthetical overrides 6.7.8p2 and specifies that in this case the terminating null character is discarded.

There is a similar special case for initializing a wchar_t array with a wide string literal.

zwol
  • 135,547
  • 38
  • 252
  • 361