在C++中反转char数组导致错误

jos*_*im5 -1 c++ arrays string

我使用以下代码来反转char数组.我的代码和错误可以在下面找到.

我的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

错误:

        Compiling...
Compile error: your program did not compile correctly:
program.c: In function 'char* reverseStr(char*)':
program.c:18: error: invalid conversion from 'char' to 'char*'
      --> 17:   }
      --> 18:   return *(reversed);
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Kon*_*lph 6

您的返回值和类型是错误的.

此外,您的声明reversed无效,并且在任何情况下都会泄漏内存.

此外,std::strlen不建议计算字符串长度而不是使用,标准库具有std::reverse反转字符串的功能.