gpt4 book ai didi

将来自键盘的 2 个输入与 strcmp 进行比较会导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:41:05 25 4
gpt4 key购买 nike

我是c语言的新学生,我只是想出了这个。我代码:

#include <stdio.h>
#include <string.h>

int main(void)
{
char str[80];

printf("Enter sth: ");
char st1 = gets(str);

printf("Enter sth: ");
char st2 = gets(str);

if(strcpy(st1,st2))
printf("Same\n");
else
printf("Different\n");

return 0;
}

我的目标是检查我从键盘输入的 2 个字符串是否相同。我编译它并收到一些警告:

hello.c: In function ‘main’: hello.c:9:16: warning: initialization makes integer from pointer without a cast [enabled by default]

hello.c:12:16: warning: initialization makes integer from pointer without a cast [enabled by default]

hello.c:14:5: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]

/usr/include/string.h:128:14: note: expected ‘char * restrict’ but argument is of type ‘char’

hello.c:14:5: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]

/usr/include/string.h:128:14: note: expected ‘const char * restrict’ but argument is of type ‘char’

输入某物: asd
输入某物: asd
输出:段错误(核心已转储)

Segmentation Fault 当你想访问它不存在的东西时,我看到这是一个错误!

我在 Stackoverflow 中搜索了一些类似的问题和 here但我不明白为什么这段代码不起作用。谢谢!

最佳答案

您正在将 char 变量的地址视为字符串并使用 strcpy 而不是 strcmp。这:

char st1 = gets(str);
char st2 = gets(str);
if(strcpy(st1,st2))

本来是:

char st1[255], st2[255];
scanf("%254s", st1);
scanf("%254s", st2);
if(strcmp(st1, st2) == 0)

关于将来自键盘的 2 个输入与 strcmp 进行比较会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19211087/

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