简体   繁体   中英

Why does sscanf need & for %d integers but not for %s strings

I am confused about the arguments in sscanf routine

#include <string.h>
char sentence[20];
char first_name[7];
char last_name[7];
int age;

strcpy(sentence, "aaaaaa bbbbbb 20");
sscanf(sentence, "%s %s %d", first_name, last_name, &age);

Why is that char arrays do not need & prefixed but integer variable does?

Thank you

A string in C is a sequence of characters followed by a '\\0' character. The name of an array in C is the address of the initial element. So for a single integer you will need to add the '&' to pass the address where you want to store the int.

In C, the name of the array represents the base address.
In sscanf() you need to pass the memory location where variable value could be stored. So & means address of , is used to get the address in case of primitive types. That is why & is used with int data type. But string being the array (followed by '\\0' ) of characters, name provides the base address.

& in the called function implies address of .

sscanf expects address of variables so that it can store the read values from the given string into those addresses (and hence in those variables).

An array name in C by itself refers to address of first array element, but for a variable, you need to specify the address of the variable.

In C, the identifier of array of character is decayed as a pointer to the first element of the array.

sscanf() function needs a pointer to a memory location to write in it, if you pass an int type, you should prefix the variable name with & which has for effect to pass the address of the variable. This way, sscanf can write directly on the memory location of the variable. You are passing an argument by reference, not by copy.

Since the array name is decayed to a pointer to the first element of the array, you do not need to prefix it with & because sscanf already access the memory location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM