为什么 scanf() 需要 &运算符(地址)在某些情况下,而不是其他情况? [英] Why does scanf() need & operator (address-of) in some cases, and not others?

查看:49
本文介绍了为什么 scanf() 需要 &运算符(地址)在某些情况下,而不是其他情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要在 scanf() 中放置一个 & 运算符来将值存储在整数数组中,而不是在将字符串存储在字符数组中时?

Why do we need to put a & operator in scanf() for storing values in an integer array but not while storing a string in a char array?

int a[5];
for(i=0;i<5;i++)
scanf("%d",&a[i]);

但是

char s[5]; scanf("%s",s);

我们需要传入存储值的地址,因为数组是指向第一个元素的指针.所以在 int/float 数组的情况下,它基本上意味着 (a+i).

We need to pass in the address of the place we store the value, since array is a pointer to first element. So in the case with int/float arrays it basically means (a+i).

但是字符串呢?

推荐答案

scanf 接受一个指针,指向您将值放入的任何内容.首先,您传递对整数中位置 i 处特定 int 的引用大批.在第二个实例中,您将整个数组传递给 scanf.在 C 中,数组和指针是同义词,可以互换使用(有点).变量 s 实际上是一个指向内存的指针,它有 5 个字符的连续空间.

scanf accepts a pointer to whatever you are putting the value in. In the first instance, you are passing a reference to the specific int at position i in your integer array. In the second instance you are passing the entire array in to scanf. In C, arrays an pointers are synonymous and can be used interchangeably (sort of). The variable s is actually a pointer to memory that has contiguous space for 5 characters.

这篇关于为什么 scanf() 需要 &amp;运算符(地址)在某些情况下,而不是其他情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆