c - StringICompare 与 char 指针不起作用

标签 c

我的这段代码有问题。 我想用两个字符指针制作 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;
}

最佳答案

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

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);

关于c - StringICompare 与 char 指针不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193417/

相关文章:

c - libcurl:使用 WriteMemoryCallback 时 curl_easy_perform 上的段错误

c - 使用 c 从主字符串中删除子字符串

C++ 二维数组函数 - 为什么第二个索引不能可变

c - 在 C 中获取两个数组差异的有效方法是什么?

命令行输入二进制数

c - 使用 Pthread 的动态矩阵乘法

c - 如何有效地评估或近似道路回旋曲线?

c - 在获取 bashrc 时启动应用程序

C 中乘法后计算器崩溃

c - 没有这样的文件或目录: Cygwin + Gcc