I have been reading C Primer Plus (5th edition) by Stephen Prata. The Program listing 11.9 is a program to show what may the puts()
function do if we declare a string and assign a value without an ending null character. (Of course this is viewed as a grammar mistake, but I want to know what error will this bug cause.) I experimented on my computer (with CodeBlocks my ide) a similar program, and tried different ways to declare the string.
For the program
#include <stdio.h>
int main()
{
char a[]={'a','b','c','d'};
char b[100]="Stack Overflow";
puts(a);
return 0;
}
in which I used a[]
to declare the string, the program indeed output some thing other than abcd
. I tried several times, and it always output abcd<
and an empty line:
output:
abcd<
If I declare the string by a[100]
, i.e. the program
#include <stdio.h>
int main()
{
char a[100]={'a','b','c','d'};
char b[100]="Stack Overflow";
puts(a);
return 0;
}
Then it seems quite normal. The program always output abcd
and an empty line after I have repeated several times:
output:
abcd
If I use the pointer to declare the string:
#include <stdio.h>
int main()
{
char *a={'a','b','c','d'};
char b[100]="Stack Overflow";
puts(a);
return 0;
}
Then it only output an empty line:
output:
Why different ways of declaring the string, which is assigned a value without an ending '\0'
yields different outputs?