- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我是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/
我是一名优秀的程序员,十分优秀!