rohaldb
rohaldb

Reputation: 588

String output not as expected

#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'?

Upvotes: 3

Views: 73

Answers (1)

kaylum
kaylum

Reputation: 14046

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';

Upvotes: 6

Related Questions