gpt4 book ai didi

c - scanf 和 char 变量问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:13 26 4
gpt4 key购买 nike

好吧,我正在阅读C for dummies,但我又遇到了scanf 问题。我早些时候写了另一个提问者有类似的问题,但修复在这里不起作用。每次编译,gcc 总是说:

MADLIB1.C: In function ‘int main()’:
MADLIB1.C:19:27: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘char ()[20]’ [-Wformat]
MADLIB1.C:21:22: warning: format ‘%s’ expects argument of type ‘char
’, but argument 2 has type ‘char ()[20]’ [-Wformat]
MADLIB1.C:23:23: warning: format ‘%s’ expects argument of type ‘char
’, but argument 2 has type ‘char ()[20]’ [-Wformat]
MADLIB1.C:25:27: warning: format ‘%s’ expects argument of type ‘char
’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
MADLIB1.C:31:52: error: expected ‘}’ at end of input

这是我的代码:

/*
MADLIBI.C Source Code
Written by Arshad Husain
*/

#include <stdio.h>

int main()
{

char adjective[20];
char food[20];
char chore[20];
char furniture[20];

/* Get the words to use in the madlib */

printf("Enter an adjective"); /* prompt */
scanf("%s",&adjective);
printf("Enter a food");
scanf("%s",&food);
printf("Enter a household chore (past tense):");
scanf("%s",&chore);
printf("Enter an item of furniture");
scanf("%s",&furniture);

/* Display the output */

printf("\n\nDon't touch that %s %s!\n", adjective, food);
printf("I just %s the %s!\n", chore, furniture);

return(0);
}

最佳答案

你不应该对数组使用 address-of,它们已经是指针了:

printf("Enter an adjective");     /* prompt */
scanf("%s",adjective);

当你使用 address-of, e.i., & 时,它变成了 char **,这不是 scanf 所期望的。

另外,对于这个例子,这样做更安全:

scanf("%19s",adjective); /* maximum 19 chars */

防止溢出。

关于c - scanf 和 char 变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11426815/

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