【问题标题】:Why doesn't C need '&' in scanf() while dealing with strings/char [duplicate]为什么C在处理字符串/字符时不需要'&'在scanf()中[重复]
【发布时间】:2020-09-12 17:57:54
【问题描述】:

我的代码非常简单,只是基本的 IO。现在,当我使用此代码时,它可以完美运行。

#include <stdio.h>

int main()
{
    int age = 0;
    char name[100]; //Unlike c++ We need to specify char limit instead of "Name", so name can't go above 99 char + 1 terinator
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Enter your name: ");
    scanf("%s", name);// dont need & for char
    printf("Your name is %s and your age is %d\n", name, age);
    return 0;
}

现在

#include <stdio.h>

int main()
{
    int age = 0;
    char name[100]; //Unlike c++ We need to specify char limit instead of "Name", so name can't go above 99 char + 1 terinator
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Enter your name: ");
    scanf("%s", &name);// dont need & for char
    printf("Your name is %s and your age is %d\n", name, age);
    return 0;
}

当我在第 10 行进行更改并添加 &name.编译器抛出此错误。这是为什么呢?

p2.c:10:17: error: format specifies type 'char *' but the argument has type 'char (*)[100]' [-Werror,-Wformat]
    scanf("%s", &name);// dont need & for char
           ~~   ^~~~~

我对 C 了解不多。

【问题讨论】:

  • 因为在第二个代码中 sn -p %s 需要 char 数组的起始地址。所以,name 存储数组的起始地址。在 char %c 中也需要地址。在char ch; ch 不会返回您需要使用&amp;ch 的地址。
  • @Sathvik: name 不存储地址 - 根据需要将名称转换为地址。

标签: c pointers


【解决方案1】:

C 中的字符串只是字符序列。因此,%s 格式说明符需要一个指向char 的指针,以便它可以将scanf 读取的任何内容写入该指针指向的内存位置的字符序列中。在您的情况下,name 是字符 array 而不是指针,但在 C 中,您通常可以在需要指针的上下文中使用数组,我们说数组 decays指向其第一个成员的指针。

【讨论】:

    【解决方案2】:

    scanf 函数接受一个指向要设置其值的变量的指针。

    对于像int这样的其他类型,我们使用&amp;运算符来指定变量的地址,而对于char[],变量name被转换为指向数组第一个元素的指针,所以我们不'不需要&amp;

    【讨论】:

    • char name[100]; 是一个数组而不是一个指针。在这种情况和许多其他情况下,它会自动转换为指向其第一个元素的指针。
    • 非常感谢,@HolyBlackCat!!。我理解了这个错误并修复了它。可以看看吗?
    • 名称指定数组,而不是地址。它被转换为指向第一个元素的指针。
    【解决方案3】:

    字符串是字符数组。数组在 C 中通过引用传递。

    因此,当您将数组传递给函数时,实际上是在传递指针。

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2010-12-28
      • 2016-11-11
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多