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]
.
Problem is what
sizeof(word - i)
actually does.Short answer: it returns pointer size (4 or 8).
More detailed answer:
word
has typechar[10]
and size10
word + 1
, the compiler will decay array to pointer to char to be able do this operation. So result type ischar *
sizeof(char *)
is 4 or 8 depending on what platform you build it (32 or 64 bits)word[sizeof(word - i)]
always refers to the same cellThere is also a second problem. In
C
, strings of text must be null terminated to indicate the size of it. Yourword
containsapple
without zero character at the end, so garbage is printed afterapple
(it may even crash program).Also, your code is more C like, in C++ this can be done like this: