Reversing a char array in C++ causing an error
I am using the following code in order to reverse a char array. My code as well as the error can be found below.
My code:
char * reverseStr(char* s) {
int i=0; //legnth of string
while(s[i]) i++;
char reversed[i];
for(int j=0; j<i; j++) {
reversed[j] = s[i-j - 1]; //look at this later
}
return *(reversed);
}
The error:
Compiling...
Compile error: your program did not开发者_StackOverflow compile correctly:
program.c: In function 'char* reverseStr(char*)':
program.c:18: error: invalid conversion from 'char' to 'char*'
--> 17: }
--> 18: return *(reversed);
Thank you in advance!
Your return value and type is wrong.
Furthermore, your declaration of reversed
is invalid and would leak memory in any case.
Also, calculating the string length instead of using std::strlen
isn’t recommended and the standard library has the std::reverse
function to reverse strings.
Well, you are returning a char instead of a char*, so you are only returning the first letter in the reversed string instead of a string. Which causes your error messages, because you try to treat a char as a char*.
Check the error message:
program.c: In function 'int itoa2(int, char*, int)':
program.c:45: error: invalid conversion from 'char' to 'const char*'
It clearly tells you what the error is: invalid cast from const char* to char
In your code i
is not const
.
char reverseStr(char* s) {
int i=0; // --->> NOT CONST
while(s[i]) i++;
char reversed[i];
for(int j=0; j<i; j++) {
reversed[j] = s[i-j - 1]; //look at this later
}
return *(reversed);
}
char reversed[i];
---> Variable Length Array in C++?? i
is supposed to be known at Compile time.
strcpy receives (char*, const char*) as parameters.However, the return type of your function is char, thus the error appears.
And char reversed[] is allocated on the stack of the function, please don't use it as a return value.
精彩评论