String output is 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 anyone explain why my output is either repeating words or printing weird numbers and letters? Is it because I didn't include '\ 0'?

+3


source to share


1 answer


Lines in C must be NUL ('\ 0') terminated. You have char arrays with no NUL terminator and therefore 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 to setting each char separately, 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';

      

+6


source







All Articles