1

可能重复:
为什么在写入字符串时会出现分段错误?

假设我有 s =“你好”。我希望它转换成 s = "Hello"。

这就是我所拥有的

# include <stdio.h>
# include <string.h>
main()
{
    char *s = " Hello";
    char *shift(char *, int);

    shift(s+1,-1);
    printf("%s", s);
}

char *shift (char *str, int units)
{
    if (units < 0)
    {
        for (; *str != '\0'; str++)
            *(str + units) = *str;
        *(str + units) = '\0';
        return str-strlen(str)-units;
    }

}

程序终止!甚至没有显示错误。我哪里错了..

最重要的是,是什么让这个程序将控制权交给操作系统来终止?

4

1 回答 1

4

您不能修改字符串文字。此外,您永远不会检查它str + units是否在字符串中,即它不会超出字符串的分配内存(假设您传递了一个真实的字符串,而不是字符串文字作为参数)。

于 2013-01-28T16:58:56.193 回答