【问题标题】:Read string C - Linux读取字符串 C - Linux
【发布时间】:2014-12-17 22:39:38
【问题描述】:

我正在尝试读取一个字符串并在Linux 中使用:

cc child.c -o child

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

int main(int argc, char *argv[]) {  

    char st[100];

    scanf("%s", &st);
    printf("%s", st);

    return 0;
}

但是我遇到了不允许我编译的警告。

child.c:在函数“main”中:
child.c:8:2:警告:格式“%s”需要“char ”类型的参数,但参数 2 的类型为“char ()[100]”[-Wformat=] scanf("%s", &st);

我该如何解决?谢谢!

【问题讨论】:

  • 对我来说很好用! (只想着改:scanf("%s", &amp;st);改成scanf("%s", st);
  • 很高兴您启用了编译器警告。

标签: c string


【解决方案1】:

在 C 中,当传递给函数时,数组名称转换为指向数组第一个元素的指针。无需在st 之前放置&amp;。改变

scanf("%s", &st);  

scanf("%s", st);

【讨论】:

    【解决方案2】:

    在 C 中,数组类型退化为指针。所以当你获取一个数组的地址时,你实际上得到了一个指向指针的指针。只需将数组本身传递给 scanf。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2011-11-01
      • 1970-01-01
      • 2015-09-29
      相关资源
      最近更新 更多