【问题标题】:StringICompare with char Pointers not workingStringICompare 与 char 指针不工作
【发布时间】:2018-11-07 16:12:34
【问题描述】:

我对这段代码有疑问。 我想用两个 char 指针制作 stringICmp,但在第一个 if 之后出现错误(程序收到 SIGSEGV,分段错误。)。 我使用带有 GDB 编译器的 Windows 10。 我用谷歌搜索了 SIGSEGV,但我不知道如何正确解决这个问题,感谢您的帮助。

#include <stdio.h>
#include <stdlib.h>
#define MAX_STR 20

int stringICmp(char *s1, char *s2);

int main() {
    char *str1 = "Hallo";
    char cmpstring[MAX_STR] = "HaLlo";

    int sicmp = stringICmp(str1, cmpstring);
    printf("\n\nString Compare non case-sensitive:\n");
    printStringCmp(sicmp);
}
void printStringCmp(int scmp) {
    printf("\nThe String Compare Result is: %d\n", scmp);
    if(scmp > 0) {
        printf("String 1 is bigger than String 2.");
    } else if(scmp < 0) {
        printf("String 1 is smaller than String 2.");
    } else if(scmp == 0) {
        printf("String 1 is equal to String 2.");
    }
}
int stringCmp(char *s1, char *s2) {
    while(*s1 == *s2 && *s1 != '\0' && *s2 != '\0') {
        s1++;
        s2++;
    }
    if(*s1 > *s2) {
        return 1;
    } else if(*s1 < *s2) {
        return -1;
    }
    return 0;
}
int stringICmp(char *s1, char *s2) {
    char *s1cpy = s1, *s2cpy = s2;
    while(*s1cpy != '\0' && *s2cpy != '\0'){
        if(*s1cpy >= 65 && *s1cpy <= 90) {
            (*s1cpy) += 32;
        }
        if(*s2cpy >= 65 && *s2cpy <= 90) {
            (*s2cpy) += 32;
        }
        s1cpy++;
        s2cpy++;
    }
    s1 = s1cpy;
    s2 = s2cpy;

    int scmp = stringCmp(s1, s2);
    return scmp;
}

【问题讨论】:

  • 请说明您如何调用stringICmp,问题的根源很可能是那里minimal reproducible example 在这里也会有所帮助。 stringCmp 是什么?
  • 还要避免65之类的幻数,写'A'而不是65等。
  • 你也应该考虑像tolower这样的函数。
  • 提示:扔掉stringICmp函数,根据stringCmp从头开始重写。
  • +1 到 @Jabberwocky 的提示,以将 stringICmp 建立在您现有的 stringCmp 上;让比较不区分大小写只需要一个小改动;我看到您从 stringICmp 内部重用 stringCmp 的动机,但是字符串复制和操作在代码复杂性方面比拥有几乎相同的 stringICmp 花费更多

标签: c


【解决方案1】:

你的代码失败的原因是你试图修改一个字符常量

int main() {
    char *str1 = "Hallo";

..
int sicmp = stringICmp(str1, cmpstring);
..

int stringICmp(char *s1, char *s2) {
    char *s1cpy = s1, *s2cpy = s2;
    while(*s1cpy != '\0' && *s2cpy != '\0'){
        if(*s1cpy >= 65 && *s1cpy <= 90) {
            (*s1cpy) += 32; <<<< right here you try to overwrite your inpout

这是不允许的。您应该对字符串的副本进行操作(而且您正在破坏您的输入,这不是礼貌的事情)

使用 strdup 复制输入字符串。

int stringICmp(char *s1, char *s2) {
    char *s1cpy = strdup(s1), *s2cpy = strdup(s2);
    while(*s1cpy != '\0' && *s2cpy != '\0'){
        if(*s1cpy >= 65 && *s1cpy <= 90) {
            (*s1cpy) += 32;
....
free(s1cpy);
free(s2cpy);

【讨论】:

    猜你喜欢
    • 2018-04-05
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多