[英]Segmentation fault in strcmp() on C
我的比较字符串的程序在第二次输入后由于“分段错误”而失败:
#include<stdio.h>
#include<string.h>
int main (void)
{
char* input1;
char* input2;
printf("type something: ");
scanf("%s", &input1);
printf("type something: ");
scanf("%s", &input2);
if(strcmp(input1, input2) == 0)
{
printf("u type the same thing\n");
}
else
{
printf("u not type the same thing\n");
}
}
输出:
sekai92@sekai92-VirtualBox:~/Desktop/C_CPP$ make compare
clang -Wall -Werror -ggdb compare.c -o compare
sekai92@sekai92-VirtualBox:~/Desktop/C_CPP$ ./compare
type something: hello
type something: hello
Segmentation fault (core dumped)
input
和input1
是未初始化的指针。 这会导致不确定的行为 (C语言标准术语)。
您需要使用malloc()
或calloc()
分配malloc()
。 或者只是使用局部数组:
char input[SIZE];
char input1[SIZE];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.