以下是昨天修改后的代码。它崩溃了我的void函数中删除tempChar的行。 我尝试使用delete [] tempChar;在我的char *函数中将tempStr作为全局变量;在删除tempChar之前先删除tempChar中的内容。两者都没有。
#include <iostream>
using namespace std;
#include <cstring>
char* string_reverse2(const char* string){
cout << "the word to reverse: " << string << endl << endl;
if (string == NULL){
return NULL;
}
int strlength = strlen(string);
char* tempStr = new char[strlength + 1];
tempStr[strlength + 1] = 0;
int index = 0;
for (int i = 0; i <= strlength; i++){
tempStr[index] = string[strlength - 1 - i];
index++;
}
cout << endl;
return tempStr;
}
void string_reverse1(char* string){
char* tempChar = string_reverse2(string);
cout << tempChar << endl;
//delete tempChar;
}
int main(){
string_reverse1("I love Friday!");
return 0;
}
=============================================== =================================== 我从我的void string_reverse1函数中获取一个const char * string作为我的参数,并尝试通过将值复制到新创建的char * tempStr来反转它。在for循环中,我能够看到const char *字符串的每个值被成功复制到tempStr;但是,tempStr似乎在for循环之外是空的。你能帮我弄清楚问题是什么吗? 非常感谢!
char* string_reverse2(const char* string) {
cout << "the word to reverse: " << string << endl << endl;
if (string == NULL){
return NULL;
}
int strlength = strlen(string);
char* tempStr = new char[strlength];
for (int i = strlen(string); i >= 0; i--){
tempStr[strlen(string) - i] = string[i];
cout << tempStr[strlen(string) - i];
}
cout << endl << endl;
//tempStr[strlen(string) + 1] = '\0';
cout << "reversed word: " << tempStr << endl;
return tempStr;
}
void string_reverse1(char* string){
const char* temp = string;
char* tempChar = string_reverse2(temp);
cout << tempChar;
}
答案 0 :(得分:0)
我认为您可以按照这些建议(see live sample)
修复您的代码#include <iostream>
#include <cstring>
using namespace std;
char* string_reverse2(const char* string) {
cout << "the word to reverse: " << string << endl << endl;
if (string == NULL){
return NULL;
}
int strlength = strlen(string);
char* tempStr = new char[strlength + 1];
// ^^^
// Ensure the NUL character at end of c-string
tempStr[strlength + 1] = 0;
int index = 0; // The inital index to fill in the reversed charactrs result
for (int i = strlength - 1; i >= 0; --i) {
// ^^ Prefer the prefix increment operator
// to avoid unnecessary copies
tempStr[index] = string[i];
// ^^^^^ Use this index to fill in tempStr[index]
cout << tempStr[index];
++index;
}
cout << endl;
// tempStr[strlength] = 0;
cout << "reversed word: " << tempStr << endl;
return tempStr;
}
void string_reverse1(const char* string) {
char* tempChar = string_reverse2(string);
cout << tempChar << endl;
// Don't forget to finally release the memory allocated in string_reverse2()
delete [] tempChar;
}
int main() {
string_reverse1("Hello");
return 0;
}
输出:
the word to reverse: Hello
olleH
reversed word: olleH
我一直在上面的代码示例的注释中指出了必要的修复。