There are conceptual errors in my answer. I only noticed after @Maniero's answer . But I could not remove it, it was already marked as accepted.
So while I do not correct / remove this response, please refer to the response for something correct and more accurate.
If the name of the array or array is already the address of the first element, why in scanf, using the primitive types (int, char, float, double) I need to pass the
You're talking about int abc[5]; scanf("%d", &abc[0]);
, right?
When you do abc
, you are getting the memory address of the first element. When you do [n]
, you "jump" n
houses and get the value contained in the n
box.
For example:
(intA) (intB) (intC) (intD) (intE)
[----] [----] [----] [----] [----]
0 1 2 3 4
If you by abc[0]
, you will get the value contained in intA
.
By% with%, you get the address that points to &abc[0]
.
When you want to read a string ( intA
) do not need?
The string reading of "%s"
will take what was typed and put in the last memory address. When using strings with static allocation, we have a character vector. The usage is like this:
char palavra[100];
scanf("%s", palavra);
Here, each character will be placed in the corresponding position. For example, the word scanf
:
(chrA) (chrB) (chrC) (chrD) (chrE)
[----] [----] [----] [----] [----]
0 1 2 3 4
[a] [b] [c] [char palavra[100];
char *ptr;
char **endereco;
ptr = palavra;
endereco = &ptr;
]
The "abc"
character is in position 0 of the a
, palavra
vector in position 1 and b
in position 2. The character in position 3 is the string terminated, the null character c
.
This is how scanf
works. It fills in the positions pointed to by the argument.
And another, why when we read strings with scanf
, even using &
, does it compile?
Because C has poor typing. Very weak.
For example:
(intA) (intB) (intC) (intD) (intE)
[----] [----] [----] [----] [----]
0 1 2 3 4
palavra
is a vector, a kind of "special constant pointer" in C. Already ptr
is a traditional pointer in C. So the assignment ptr = palavra
is respecting all typos.
endereco
, in turn, is another pointer. A pointer to a pointer. So it makes sense to assign endereco = &ptr
makes sense and respects typing.
However, the C language can not differentiate runtime in time from the variable types. And at compilation level C treats pointers as pointers, regardless of which type pointed to. Of course, the compiler will complain, issue warnings, but if you had it done that way, you know.
C do not worry if you shoot your own foot. Language assumes that the programmer knows what he is doing, so he will not offer him any security against his own mistakes. If you are making a macacada, that of the philosophy of language accept its macacada as law.