3
#include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { char hello[5]; hello [0] = 'H'; hello [1] = 'e'; hello [2] = 'l'; hello [3] = 'l'; hello [4] = 'o'; char world[5]; world [0] = 'W'; world [1] = 'o'; world [2] = 'r'; world [3] = 'l'; world [4] = 'd'; printf ("%s %s!\n", hello, world); return EXIT_SUCCESS; } 

When I run the above code I get:

Hello WorldHello! 

Can someone please explain why my output is either repeating words or getting weird numbers and letters being printed? Is it because I haven't included a '\0'?

1
  • Yes; it is because you did not null terminate your character arrays, so you don't have any strings (because strings are null terminated) and you invoked undefined behaviour by passing two non-strings to printf() and told it that it was given two strings. Anything could have happened. You were lucky that what did happen was basically benign. You might care to meditate on what you see if you reverse the order of defining hello and world. Commented Jun 18, 2015 at 0:26

1 Answer 1

6

Strings in C need to be NUL ('\0') terminated. What you have are char arrays without a NUL terminator and hence are not strings.

Try the following. Double quotes produce strings (NUL terminator is added automatically).

const char *hello = "Hello"; const char *world = "World"; 

Or your original approach of setting each char seperately in which case you need to explicitly set the NUL terminator.

char hello[6]; hello [0] = 'H'; hello [1] = 'e'; hello [2] = 'l'; hello [3] = 'l'; hello [4] = 'o'; hello [5] = '\0'; char world[6]; world [0] = 'W'; world [1] = 'o'; world [2] = 'r'; world [3] = 'l'; world [4] = 'd'; world [5] = '\0'; 
Sign up to request clarification or add additional context in comments.

4 Comments

Or char hello[] = "Hello";?
@JonathanLeffler Yes. But you knew that :-) So are you suggesting one way over the other for a particular reason? In either case I think it's good to have const to indicate that the string contents should not be changed.
Well, char hello[] = "Hello"; isn't creating a string constant; it is an automatically sized and null-terminated initialized modifiable array of characters. Granted, an optimizing compiler might convert the written out initialization into the equivalent initializer, but this is definitely not a const -- though the const could be added. Also, there might be more storage used by a pointer and a string literal than by an array; not a major consideration on most systems, though. You might also note that C allows char hello[5] = "Hello"; but C++ does not. Extra information for the OP.
It is not NULL, but ASCII-NUL ('\0'). NULL is the null pointer and can (should?!) be void *, which you most likely do not want to assign to char.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.