程序在 C 中移动字符串时终止



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

假设我有 s = "你好"。我希望它转换为 s = "你好"。

这就是我所拥有的

# 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 != ''; str++)
            *(str + units) = *str;
        *(str + units) = '';
        return str-strlen(str)-units;
    }
}

该计划即将终止!甚至没有显示错误。我哪里出错了..

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

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

最新更新