gpt4 book ai didi

c - C 上的 strcmp() 中的段错误

转载 作者:行者123 更新时间:2023-11-30 18:41:23 25 4
gpt4 key购买 nike

我的字符串比较程序在第二次输入后失败并出现段错误:

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

最佳答案

inputinput1 是未初始化的指针。这会导致undefined behaviour (C语言标准术语)。

您需要使用malloc()calloc()分配内存。或者简单地使用本地数组:

char input[SIZE]; 
char input1[SIZE];

关于c - C 上的 strcmp() 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21976714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com