2

我正在自己编写 reverseString 函数。(供测试使用)而且我使用iOS平台运行我的c代码,这听起来很奇怪,但再次用于测试......

这是我的代码:

-(char *) reverseString:(char *)str
{
    char *end = str;
    char tmp;

    if (str)
    {
        while (*end) { end++; }
        --end;
        NSLog(@"%c", *end);
        while (end>str)
        {
            tmp = *str;
            *str = *end;
            str++;
            *end = tmp;
            end--;
        }
    }
    NSLog(@"%s", str);
    return str;
}

通过调用运行函数后:

char *testChar = "abcd";
[self reverseString:testChar];

我在线收到错误:

*str = *end;
Thread 1: EXC_BAD_ACCESS(code=2, address=0x2de4)

我真的不知道这里的指针有什么问题......有人知道吗?

4

1 回答 1

4

您不能修改字符串文字。请改用 char 数组。

char testChar[] = "abcd";
于 2012-11-20T10:35:37.470 回答