A scanf()
must be passed as the second parameter (or terecero, etc. if there is more than one) a memory address, because it is in that direction where it will leave the data reccogido keyboard.
When you read an integer variable, or float, it is usual to use &variable
to get the memory address where that variable is, and pass that address to scanf()
.
When you read strings, the most usual thing is to have a pointer pointing to a memory area where you intend to read the string (although this is not your case), for example:
char *nombre;
nombre = malloc(20); // Reservar sitio para 20 caracteres
In this case, since nombre
is a pointer, you would call scanf()
with:
scanf("%s", nombre);
then the value of nombre
already points to the area where we want to leave the data. You should not use &nombre
here, because in that case the data would be saved in the pointer , instead of in the direction pointed to by the pointer . Of course that would be wrong, since the pointer is not a place to store characters.
In your case, what you have is an array of char:
char nombre[20];
It happens that in C, the name of an array as part of an expression is equivalent to the memory address where the first element of that array is. That is, if you put:
scanf("%s", nombre);
the compiler sees:
scanf("%s", &nombre[0]);
and in that sense we can omit the &
in front of an array when we want to obtain its address.
Moreover, scanf("%s", &nombre)
, if you put purist, it is incorrect from the point of view of the types, since &nombre
gives us the address of the array instead of the address of the first element of the array. Although both are the same address at the end, their types do not match, since &nombre
is a pointer to array of characters , while &nombre[0]
(or nombre
to dry) is a < em> pointer to character .
Note on security .
Using scanf()
to read strings is insecure because typically your string has a limited size (20 in this case), but at scanf()
you do not tell the maximum number of characters to read. The user could enter more than 20 with unpredictable results. It is recommended to use fgets()
instead, which does allow you to specify a maximum number of characters to read, like this:
fgets(nombre, 20, stdin);