scanf中什么时候用&,什么时候不用
source link: https://blog.51cto.com/u_15740905/5569963
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
scanf中什么时候用&,什么时候不用
原创1.首先scanf是格式输入函数,&是取地址运算符,使用scanf时,对于本身无法表示地址信息的,往往要加&来“获取地址”,本身表示的就是地址信息的,就不需要加&来取地址。判断的依据可以看,scanf后面的参数,是否能够反应地址信息,不能你就需要使用&或使用指向该位置的指针的方式来传给给scanf地址,能就不需要取地址。
2.记住常见的类型
(1). 整型变量类型
int main
{
int a=0;
int b=0;
scanf("%d",&a);
b=a;
printf("%d\n",b);
return 0;
}
(2).字符串类型
C语言规定,字符串变量就表示这个字符串储存的首地址,并且是连续储存,所以知道了首地址,因此读取字符串时,就不需要&,因为它本身就代表地址:
int main()
{
char str = 0;
char password[10] = { 0 };
printf("输入字符串:>");
scanf("%s", password);
printf("%s\n", password);
return 0;
}
(3).数组同理,数组变量名代表数组存储空间的首地址,因此也不需要加取地址。
(4).指针变量类型
int main()
{
int a;
int* b = &a;//取地址来初始化指针
scanf("%d", b);
return 0;
}
(5).使用下标访问来赋值,则需要指定其地址,因为下标获得的是值不是地址。
int main()
{
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i = 0;
scanf("%d", &i);
printf("%d\n", arr[i]);
return 0;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK