0

这是我的代码:

    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:第 7 行:1931 总线错误“$3”.out

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

4

3 回答 3

8

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

char *str = strdup("Forest Gump"); 
reverseStr(str); 
cout << str; 
free(str);
于 2010-08-16T20:31:34.897 回答
4

字符串文字是只读内存,您不能反转它们,也不能以任何方式修改它们而不会遇到未定义的行为。

首先将您的字符串复制到缓冲区中,然后传入缓冲区。或者声明一个数组而不是指针,并使用字符串初始化器初始化该数组。

于 2010-08-16T20:30:29.157 回答
0

错误出现在 bash/shell 脚本中,而不是在您的程序中。您也可以发布 bash 脚本吗?

于 2010-08-16T20:31:20.950 回答