gpt4 book ai didi

c++ - 反转 c 类型的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:49 25 4
gpt4 key购买 nike

这是我的代码:

    void reverseStr(char *str)
{
if (str == NULL) return;
int i=0, j=strlen(str) -1;
while(i<j)
{
char temp = str[j]; //i think this is the cause of the problem
str[j] = str[i];
str[i] = temp;
i++;
j--;
}
}

这里是它的名字:

int main()
{
char *str = "Forest Gump";
reverseStr(str);
cout << str;
}

这是我的错误:

/Applications/TextMate.app/Contents/SharedSupport/Bundles/C.tmbundle/Support/bin/bootstrap.sh: line 7: 1931 Bus error "$3".out

有什么想法吗?提前致谢。

最佳答案

Str 指向一个固定的字符串。您正在就地修改它。换句话说,您试图更改文本文字。试试这个:

char *str = strdup("Forest Gump"); 
reverseStr(str);
cout << str;
free(str);

关于c++ - 反转 c 类型的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3497022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com