simple question about strings
hello, I'm trying to learn about strings and I wrote this simple piece of code to try and print out: ABCD
but it prints out some weird characters after D
it puts out: ABCD "
and some other symbol not on my keyboard, does anyone know why?
thank you
here's the code I wrote:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main() {
char string1 [] = { 'A' , 'B' , 'C' , 'D' } ;
printf("%s",string1);
getchar();
}
Re: simple question about strings
In C, a string is a collection of characters terminated by the null character, which is simply the character with value zero. Your code has a collection of characters, but does not include a null character, so it's not a string. printf()'s %s conversion specifier expects a string (really, a pointer to one), so what you're passing causes undefined behavior. You could do:
Code:
char string1[] = { 'A', 'B', 'C', 'D', 0 };
You could also write this as:
Code:
char string1[] = "ABCD";
In this case, "ABCD" automatically includes the null character for you.
Your code results in undefined behavior, which technically means anything can happen. What's really happening, though, is that there is random junk after the 'D' in your array that printf() prints out. It will print out as much random junk as it can until it finds a null character, or if you're on a modern operating system, you try to read memory that's outside of your address space.