gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:12:35 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com