我对此代码有疑问。
我想用两个char指针制作stringICmp,但是在第一个if之后出现错误(程序收到SIGSEGV,Segmentation fault。)。
我将Windows 10与GDB编译器一起使用。
我用谷歌搜索了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/