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;
}
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 indexsizeof(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>
usingnamespace std;
int main()
{
char charArray[] = "hello";
for (int i = sizeof charArray / sizeof( char ) - 2; i >= 0; i--)
{
cout << charArray[i];
}
}