#include <stdio.h>
#include <string.h>
int scomp(char* x, char* y);
int main(void)
{
printf("gimme a string: ");
char* str1;
scanf("%s",str1);
printf("gimme another string: ");
char* str2;
scanf("%s",str2);
printf("comparing them......n__________n");
if(scomp(str1,str2) == 0)
{
printf("yup, they are the samen");
}else if(scomp(str1,str2)== 1){
printf("They are different buddy..n");
}
return 0;
}
int scomp(char* x, char* y)
{
int n=0;
while(x[n] != ' ')
{
if(x[n] == y[n])
{
n++;
}else{
return 1;
}
}
return 0;
}
它给了我细分故障11,我在最后一部分中写的函数必须有问题,该功能应该比较字符串。有什么问题?
char* str1;
scanf("%s",str1);
char* str2;
scanf("%s",str2);
str1
和 str2
是未初始化的,并且由于它们是指针,因此您基本上将scanf的结果写入内存中的随机位置。
这就是为什么您会得到分割故障(您的程序试图在不被授权写入的内存段上写入)