【发布时间】: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