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 ?
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 ?
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.