Reputation: 851
I'm learning C and am currently experimenting with storing strings in variables. I put together the following to try different stuff.
#include <stdio.h>
int main() {
char *name = "Tristan";
char today[] = "January 1st, 2016";
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\n'};
printf("Hello world!\n");
printf("My name is %s.\n", name);
printf("Today is: %s.\n", today);
printf(newyear);
return 0;
}
After compiling this code and running it, I get the following results:
Hello world!
My name is Tristan.
Today is: January 1st, 2016.
Happy New Year!
January 1st, 2016
Now this is pretty much what I would expect, by why would "January 1st, 2016" get printed out again at the end of the program's output?
If I take the "\n" out of the "newyear" array, it will not do this.
Would someone please explain why this is?
Upvotes: 2
Views: 163
Reputation: 34575
newyear
should finish with a '\0'
instead of the newline
, to be a C string. You can then put the newline
in the printf
statement, like the others:
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\0'};
//...
printf("%s.\n", newyear);
Or, you can add the string terminator to the array, and use the printf
as you did:
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\n','\0'};
//...
printf(newyear);
In your first two examples, a string defined as "my string"
automatically has the '\0'
appended, by the compiler.
Upvotes: 0
Reputation: 15229
newyear
misses a trailing null byte, so printf
ing it is undefined behavior.
Only string literals implicitly append a null byte. You explicitly initialize every character, so no null byte is appended.
Undefined behavior means that something the standard does not define in this occasion will happen. That includes nothing happening, you bursting into tears, or, yes, printing some string twice.
Just add an additional character, i.e., a null byte to the array to resolve the problem:
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\n', '\0'};
Note that no sane person initializes an automatic char
array with a string like that. Just stick to string literals! (I think you did it just for learning purposes, though.)
Upvotes: 5
Reputation: 133557
This because you are defining newyear
directly as a char
array and not through the string literal ""
syntax. This prevents the compiler from adding a trailing \0
character which is required to mark the end of a string.
Since both newyear
and today
reside on stack, in this case they have contiguous storage there so printf
keeps after the \n
of newyear
and prints contents of memory until a \0
is found.
Upvotes: 0
Reputation: 409136
Remember that strings in C are terminated by the special '\0'
character.
Not having this terminator at the end of data that is treated as a string will lead to undefined behavior as the string functions pass the end of the data searching for the terminator.
Upvotes: 0