C - 为什么这个表达式 *q = *(q + 1) 在处理字符串时产生错误?

标签 c

void delchar(char *s, char c){
  char *p, *q = NULL;
  for(p = s;*p != '\0'; p++){
    if(*p == c){
        q = p;
        do{
            *q = *(q + 1);
            q++;
        }while(*q != '\0');
    }
 }
}

我想使用这段代码删除字符串中的特定字母,因此我创建了一个指针 p 来扫描字符串,创建另一个指针 q 将元素移到该特定字母后面并覆盖它。但事实证明,用于移动和覆盖的表达式 *q = *(q + 1) 出错了“程序收到信号 SIGSEGV,段错误”。我只是不知道其原因。

最佳答案

尽管您不会因此而出现段错误,但您的算法存在缺陷。即使删除了一个字符,p 光标也会前进。

使用while而不是for:

#include <stdio.h>
#include <string.h>

void delchar(char *s, char c)
{
    char *p, *q = NULL;

    p = s;
    while (*p != '\0')
    {
        if (*p == c)
        {
            q = p;
            do {
                *q = *(q + 1);
                q++;
            } while(*q != '\0');
        }
        else
            p++; // Advance cursor only if no character was deleted
    }
}

int main()
{
    char str[1024];
    strcpy(str, "Yes or  no?");
    delchar(str, ' ');
    printf("%s\n", str);

    return 0;
}

输出:

Yesorno?

出现段错误的一个原因是尝试更新字符串文字。字符串文字不会被修改。它们与字符数组完全不同。主要区别是您无法覆盖它们的内容。

int main()
{
    char *str = "to to"; // string literal
    delchar(str, ' '); // segmentation fault

    char array[] = "to to"; // array of char
    delchar(array, ' '); // no segmentation fault
    printf("%s\n", str);

    return 0;
}

您可以像上面那样使用 strcpy() 复制字符串,或者您可以使用字符数组而不是字符串文字。

关于C - 为什么这个表达式 *q = *(q + 1) 在处理字符串时产生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837104/

相关文章:

c - 用于定期监听同一本地主机上的多个进程的最佳进程间消息传递模式

c - 为什么这个 execlp() 函数没有执行?

c - 如果 jiffies 的分辨率为毫秒,usecs_to_jiffies 如何将 usecs 转换为 jiffies?

c++ - 如何确保 C/C++ 代码中不缺少 doxygen 样式的文档注释?

c - 计算整数中不同数字的最有效方法是什么

c - 背包问题记忆化输出错误的解决方案

c - 开关和外壳出错?

c - 为什么我的 C 动态数组给我访问冲突?

c++ - 变量大小取决于语言机器实现是什么意思?

C scanf 字符串数组