gpt4 book ai didi

c - 比较 C 中两个字符串的问题(段错误)核心转储

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

<分区>

我创建了一个 struct 来对两个指针变量进行分组,这样我就可以将地址存储在这些变量上。然后我实例化该结构并引用 main 竞赛中的两个变量。根据用户输出比较两个字符串并返回所需的结果。

代码在这里

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>

typedef struct
{
char *name;
char *name2;
} names;

int main()
{
names nm;
printf("Please enter first string: ");
scanf("%s", nm.name)
printf("Please enter second string: ");
scanf("%s", nm.name2);

if(strcmp(nm.name, nm.name2) == 0)
printf("Strings %s and %s do match\n", nm.name, nm.name2);
else
printf("Strings %s and %s do not match\n", nm.name, nm.name2);
return 0;
}

我试过 printf("%s", &nm.name);

我是 C 语言的新手。谢谢!

没有 struct 和指针变量的例子

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>

int main()
{
char name[20];
printf("Please enter first string: ");
scanf("%s", &name);
char name2[20];
printf("Please enter second string: ");
scanf("%s", &name2);

if(strcmp(name, name2) == 0)
printf("Strings %s and %s do match\n", name, name2);
else
printf("Strings %s and %s do not match\n", name, name2);
return 0;
}




gcc -Wall -Wextra -Wformat -pedantic -o strcmp strcmp.c

strcmp.c: In function ‘main’:
strcmp.c:10:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
strcmp.c:11:2: warning: ISO C90 forbids mixed declarations and code [-pedantic]
strcmp.c:13:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
strcmp.c:15:2: warning: implicit declaration of function ‘strcmp’ [-Wimplicit-function-declaration]

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