Hi i am fairly new in C language and i was trying to understand the strings. As i know, strings are just an array of characters and there shouldn't be a difference between char a[]= "car"
and char a[] = {'c','a','r'}
.
When i try to print the string as:
char a[] = "car";
char b[] = "testing the cars";
printf("%s", a);
the output is just car and there's no problem.But when i try to print it as:
char a[] = {'c','a','r'};
char b[] = "testing the cars";
printf("%s", a);
it's printing the b too. Can you explain what's the reason of it?
CodePudding user response:
The %s
specifier of printf()
expects a char*
pointer to a null-terminated string.
In the first case, a
and b
are both null-terminated. Initializing a char[]
array of unspecified size with a string literal will include the literal's null-terminator '\0'
character at the end. Thus:
char a[] = "car";
is equivalent to:
char a[] = {'c', 'a', 'r', '\0'};
In the second case, a
is NOT null-terminated, leading to undefined behavior, as printf("%s", a)
will read past the end of a
into surrounding memory until it eventually finds a '\0'
character. It just happens that, in your case, b
exists in that memory following a
, but that is not guaranteed, the compiler can put b
wherever it wants.