A trick to teach you when to add & to scanf and when not to add &

1. Summary:

A simple sentence is:

For those that cannot represent the address information , & should be added; if the address information itself represents the address information, there is no need to add &

2. Why & (take the address character)?

principle: 

When scanf reads, we need to tell it where to store the data. At this time, we need to tell it the address

Then we judge whether to add &, we only need to see whether the parameter after scanf can represent the address, if it can represent the address, then there is no need to add &, if it cannot represent the address, we need to add &

3. When do you not need to add &?

Generally, there are many cases where & is added, so let’s directly look at the cases where & is not added:

(1) Pointer

The pointer is originally the address, there is no doubt that there is no need to add &

int a=0;
int *p=&a;   //取a的地址放入p中(int *是p变量的类型)

scanf("%d",p);

(2) String variable

The string variable represents the first address of the string storage, and it is stored continuously, so knowing the first address does not need &

char *str=0;

scanf("%s",str)
char str[20]={0};

scanf("%s",str);

(3) Array variable name (pay attention here to see if it is a subscript access)

Do not add & : there is no subscript access here

int arr[10]=0;

for(int i=0;i<10;i++)
{

   scanf("%d",arr+i);

}

To add & : here is the subscript access, and its address must be specified, because the value obtained by the subscript is not the address

int arr[10]=0;

for(int i=0;i<10;i++)
{

   scanf("%d",&arr[i]);

}


 

Guess you like

Origin blog.csdn.net/qq_73017178/article/details/131711144