我不明白为什么我的 C 代码中会出现分段错误

  • 本文关键字:错误 分段 代码 明白 c
  • 更新时间 :
  • 英文 :

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

str1str2未初始化的,并且由于它们是指针,因此您基本上将scanf的结果写入内存中的随机位置。

这就是为什么您会得到分割故障(您的程序试图在不被授权写入的内存段上写入)

最新更新