Reversing a word?

So here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char word1[6] = "hello";
    char word2[6];
    int i,k;
    i= strlen(word1)-1;
    k=0;
    while(i>=0){
    word2[k]=word1[i];
    i--;
    k++;
    }
    printf("%s", word2);

    return 0;
}


My output is: elloh_hello

Whats weird is that word2 is limited to 6 characters why is it showing me 12?
The end of a C-Style character string is indicated with a zero value.

When you feed a C-Style character string to printf, it will print it until it comes to the end of the string. The end of the string is the first zero value. word1 has a zero value at the end of it; word2 does not. It seems that word1 sits right next to word2 in your memory, so when you printf word2, you're getting word1 as well.
Topic archived. No new replies allowed.