[英]Why we need to specify address of variable and not name of variable while using scanf function
Why do we need to specify the address of variable and not the name of variable while using scanf function for eg: scanf("%d",&a);
为什么我们在使用 scanf 函数时需要指定变量的地址而不是变量的名称,例如:
scanf("%d",&a);
why we use & instead we could have written like this scanf("%d",a);
为什么我们使用 & 代替我们可以这样写
scanf("%d",a);
so why we need to use address while using scanf()
?那么为什么我们需要在使用
scanf()
使用 address 呢?
scanf
would implicitly want an address at all cases, because the variable you will have as input must be stored somewhere in the memory, and using &variable_name
you are assigning a pointer addressing the variable's location. scanf
在所有情况下都隐含地需要一个地址,因为您将作为输入的变量必须存储在内存中的某处,并且使用&variable_name
分配一个指向变量位置的指针。
In case of arrays/strings, you can go without using &
as because the array/string passed is infact a pointer to where the first value/character is stored.在数组/字符串的情况下,您可以不使用
&
因为传递的数组/字符串实际上是指向存储第一个值/字符的位置的指针。 (from where you can iterate over it using pointer arithmetic, for eg: +4 for int) (从那里您可以使用指针算法对其进行迭代,例如:+4 表示 int)
above answers and comments gives you technical reasons but in laymen terms以上答案和评论为您提供了技术原因,但在外行方面
so your question is basically why scanf
cannot take just name of variable instead of the address.所以你的问题基本上是为什么
scanf
不能只取变量名而不是地址。
You use scanf()
to put something in a variable right?您使用
scanf()
将某些内容放入变量中,对吗?
Now lets suppose you want to deliver a letter , can you deliver it by just giving the name of the person ?现在让我们假设你想投递一封信,你能通过提供这个人的名字来投递吗? NO
不
You need to put address on it then the postman will reach that address, the postman does not need to know the name of receiver he only needs to know the address.你需要在上面写上地址,然后邮递员就会到达那个地址,邮递员不需要知道收件人的名字,他只需要知道地址。
Your scanf
like that postman it needs the address of memory location to deliver that value to the variable you want.您的
scanf
就像邮递员一样,它需要内存位置的地址才能将该值传递给您想要的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.