Arrays and reading them in reverse, please help!

Writing a program that holds an array of my name read
in from the keyboard and display it backwards.

the code im using is:

#include <iostream>
using namespace std;

void invertArray(char[], int);

int main()
{
char name [8] = "Ashleigh";

cout << name << endl;
invertArray(name, 7);
cout << name << endl;
return 0;
}

void invertArray(char arr[], int count)
{
int temp;
for (int i = 0; i < count / 2; ++i)
{
temp = arr[i];
arr[i] = arr[count - i - 1];
arr[count - i - 1] = temp;
}
}

There is nothing wrong with this code so why cant i compile it and why does it keep saying initializer-string for array of chars is too long??
I dont know how to fix that. Does anyone know why its saying this?

There is nothing wrong with this code

But there is something wrong, your error message is telling you that.

why does it keep saying initializer-string for array of chars is too long??

Because you said your array has 8 elements but you're trying to initialize the array with 9 elements. Don't forget that C-strings have a termination character, the '\0' character.

I dont know how to fix that.

Increase the size of your array. Your array must be at least 10 in this case. Or just let the compiler determine the length.
char name[] = "Ashleigh";

Edit:
Actually the array must be at least 9 characters not 10.
Last edited on
Thank you sooo much!!
Topic archived. No new replies allowed.