为什么scanf()函数中的字符串不使用“&”?

下面是Scanf的语法。它需要两个论点:

null
scanf("Format Specifier", Variable Address);Format Specifier: Type of value to expect while inputVariable Address: &variable returns the variable's memory address.

对于字符串(字符数组),变量本身指向所讨论数组的第一个元素。因此,不需要使用“&”运算符来传递地址。

C

// C program to illustrate  not using "&"
// in scanf statement
#include<stdio.h>
int main()
{
char name[25];
// Syntax to scan a String
scanf ("%s", name);
// Comparing base address of String with address
// of first element of array which must return
// true as both must be same
printf ("(Is Base address = address of first element)? %d",
(name == &name[0]));
}


输出:

(Is Base address = address of first element)?1

要点

  1. “&”用于获取变量的地址。C没有字符串类型,字符串只是一个字符数组,数组变量存储第一个索引位置的地址。
  2. 默认情况下,变量本身指向基址,因此要访问字符串的基址,不需要添加额外的“&”

本文由 阿吉特 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享