Search code examples
c++reversec-stringsfunction-definition

Why is this c++ program to reverse a word not working


I am extremely new to c++ and wrote this program to reverse a word. What I tried was to basically loop through an array and swap first letter with the last, second with the second last etc. However the result is some wired characters ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Ω ⌠7p≈╗. I don't want a work-around since there are plenty of examples online. I just want to know why what I am doing wont work.

#include <iostream>
using namespace std;

int main()
{
    char word[10];
    for (int i = 0; i < 10; i++)
    {
        word[i] = word[sizeof(word - i)];
    }

    cout << word << endl;

    return 0;
}

It is also giving me this warning warning C6001: using uninitialized memory 'word'. But I though I initialized the memory by doing char word[10].


Solution

  • Problem is what sizeof(word - i) actually does.

    Short answer: it returns pointer size (4 or 8).

    More detailed answer:

    • word has type char[10] and size 10
    • when you do word + 1, the compiler will decay array to pointer to char to be able do this operation. So result type is char *
    • now sizeof(char *) is 4 or 8 depending on what platform you build it (32 or 64 bits)
    • so word[sizeof(word - i)] always refers to the same cell

    There is also a second problem. In C, strings of text must be null terminated to indicate the size of it. Your word contains apple without zero character at the end, so garbage is printed after apple (it may even crash program).

    Also, your code is more C like, in C++ this can be done like this:

    int main()
    {
        std::string word{"apple"};
        std::string reversed{word.rbegin(), word.rend()};
        std::cout << word << '\n';
        std::cout << reversed<< '\n';
    
        return 0;
    }