unexpected whitespace in char array output

I wrote this code trying to reverse a char array. Can someone please tell me why there is a whitespace in the output? I'm already accounting for the NULL character by using "sizeof(charArray) - 1" so I'm really confused.... The output of this code is " olleh" but I was expecting "olleh" (no whitespace). Any help would be great. My code is below:

#include <iostream>
using namespace std;

int main() {

char charArray[] = "hello";

for (int i = sizeof(charArray) - 1; i >= 0; i--) {
cout << charArray[i] << flush;
}

return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main() {
    
    char charArray[] = "hello there";
    
    for (int i = sizeof(charArray)/sizeof(char) - 2; i >= 0; i--) {
        cout << charArray[i];
    }
    cout << "\ntada!\n";
    return 0;
}
Last edited on
AaronBoyd wrote:
I'm already accounting for the NULL character by using "sizeof(charArray) - 1"

That is, indeed, the number of non-null chars in the array. However, you are failing to also account for the fact that array indices count from 0 (in c++).
The last non-null element will actually have index sizeof(charArray)-2.

What will be output for the null character at index sizeof(charArray)-1 appears to depend on the system. Your code actually works OK on cpp.sh but not on my terminal implementation, which, like yours, outputs a blank.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
   char charArray[] = "hello";
   for (int i = sizeof charArray / sizeof( char ) - 2; i >= 0; i--)
   {
       cout << charArray[i];
   }
}
Last edited on
Got it. Kinda feel like a dummy, but hey, I'm still really new to C++. Thanks for the help, it makes sense now!
Topic archived. No new replies allowed.