为什么scanf需要&;扫描整数时,而不是扫描字符串时?
当我使用scanf获取整数时,我必须使用address操作符为什么scanf需要&;扫描整数时,而不是扫描字符串时?,c,C,当我使用scanf获取整数时,我必须使用address操作符& int number; scanf("%d",&number); 但是,这不适用于扫描字符串 char word[256]; scanf("%s",word); 必须使用。当我使用&operator时,它不起作用。这是为什么。数组的名称表示c中数组的地址。 在C语言中,字符串是字符数组,所以默认情况下它给出字符串的地址在int的情况下,我们使用&作为变量的地址 遵循此链接&用于获取变量的地址。C没有字符串类型,字符串只是
&
int number;
scanf("%d",&number);
但是,这不适用于扫描字符串
char word[256];
scanf("%s",word);
必须使用。当我使用&operator时,它不起作用。这是为什么。数组的名称表示c中数组的地址。
在C语言中,字符串是字符数组,所以默认情况下它给出字符串的地址
在int的情况下,我们使用&作为变量的地址
遵循此链接
&
用于获取变量的地址。C没有字符串类型,字符串只是一个字符数组,数组变量存储第一个索引位置的地址。
默认情况下,变量本身指向基址,因此要访问字符串的基址,不需要添加额外的&
int number;
scanf("%d",&number);
资料来源:Geeksforgeks
#include <stdio.h>
#include <stdlib.h>
int main()
{
char word[256];
printf("%p \n", word);
// 0x7ffeefbff450
printf("%p \n", &word[0]);
// 0x7ffeefbff450
// Wrong
printf("%p \n", &(&word[0]));
// Meaningless to ask the address of an address
return 0;
}
名称word
相当于数组中第一个元素的地址
数组单词中的第一个元素是单词[0]
,它的地址是&单词[0]
&
仅适用于变量名称,不适用于变量地址
number
不是数组,因此number
是变量的名称而不是地址
要获取变量编号
的地址,请执行编号
&(&number)
对您有意义吗
因为当我们输入一个整数“a”时,它是生成的口袋的名称,它的地址是其他的。我们需要指向输入值应该存储的地址
& is the address operator in C, which tells the compiler to change the
real value of this variable, stored at this address in the memory.
但是对于字符串/字符数组,它已经指向第一个位置
所以,你可以得到它的任何口袋的价值,它会增加
(其数据类型的大小*pocket id)
像-str[4]一样,我们希望访问它,然后它将访问str+1*4的地址
它将给出字符串的第5个字符。C中的字符串基本上是指向char数组第一个条目的指针,因此通过给函数字符串,您已经给了它所需的指针,如果执行&String,则尝试为其提供指向字符串开头的指针。传递给
scanf
的参数必须是指针。扫描字符串时,我们不使用&
,因为word
也意味着&word[0]
或&word
,即字符数组的起始地址可能重复
int number;
scanf("%d",&number);
& is the address operator in C, which tells the compiler to change the
real value of this variable, stored at this address in the memory.