【问题标题】:How does scanf() work for strings in C99? [duplicate]scanf() 如何处理 C99 中的字符串? [复制]
【发布时间】:2020-09-20 14:21:14
【问题描述】:

所以我正在制作一部关于学习 C 语言的纪录片,我想在指针和输入中做例子。基本上,我使用 C99 制作了一个像这样的Hello, (name). 程序:

#include <stdio.h>

int main() {
    char *name;
    printf("What's your name? ");
    scanf("%s", name);
    printf("Hello, %s.\n", name);
}

当我尝试编译它时,它给我的错误是:

C3.c:5:48: error: variable 'name' is uninitialized when used here [-Werror,-Wuninitialized]
    printf("What is your name? "); scanf("%s", name);
                                               ^~~~
C3.c:4:17: note: initialize the variable 'name' to silence this warning
    char *name;
               ^
                = NULL
1 error generated.
<builtin>: recipe for target 'C3' failed
make: *** [C3] Error 1

于是我将第 2 行修改为char *result = "";,这一次确实有效,但输出是这样的:

What's your name? Bro
Segmentation fault

这让我有点困惑,因为我实际上并不习惯 scanf() 函数。

所以我的问题是,在 C99 中使用 scanf() 通过输入获取字符串,之后没有任何奇怪的输出,有什么更好的方法?

【问题讨论】:

  • 我很确定 int main(void) 在 C99 中是首选。 int main() 已经很老了。

标签: c input scanf


【解决方案1】:

scanf 不分配任何内存。您需要自己分配字符串的内存。您还应该指定允许读取scanf 的长度以避免缓冲区溢出。

例如:

char name[21]; // 20 chars plus the null-terminator
printf("What's your name? ");
scanf("%20s", name);

【讨论】:

  • scanf("%19s", name); 会更好。
  • @WilliamPursell 好点,谢谢!编辑了关于它的解释。
  • 很好地解释了char * 问题。我现在就试试。
猜你喜欢
  • 1970-01-01
  • 2021-03-24
  • 2013-06-21
  • 1970-01-01
  • 2019-01-22
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多