There are conceptual errors in my answer. I only noticed after the reply by @Maniero. But I couldn’t remove it, it was already marked as accepted.
So while I am not correcting/removing this response, refer to his answer to something correct and more precise.
if the name of the vector or matrix is already the address of the first element, why in the scanf, using the primitive types (int, char, float, double) I need to pass the address
Are you talking about int abc[5]; scanf("%d", &abc[0]);
, right?
When you do abc
, you are picking up the memory address of the first element. By doing [n]
, you "jump" n
houses and takes the value contained in the house n
.
For example:
(intA) (intB) (intC) (intD) (intE)
[----] [----] [----] [----] [----]
0 1 2 3 4
If you by abc[0]
, you will take the value contained in intA
.
At once &abc[0]
, you take the address that points to intA
.
when we want to read a string ("%s"
) don’t need?
The string reading of scanf
will take what was typed and put it in the past memory address. When using strings with static allocation, we have a character vector. The use is like this:
char palavra[100];
scanf("%s", palavra);
Here, each character read will be placed in the corresponding position. For example, the word "abc"
:
(chrA) (chrB) (chrC) (chrD) (chrE)
[----] [----] [----] [----] [----]
0 1 2 3 4
[a] [b] [c] [\0]
The character a
was at position 0 of vector palavra
, b
in position 1 and c
at position 2. The character at position 3 is the string terminator, the null character \0
.
That’s how the scanf
. It fills the positions pointed out by the argument.
And another, why when we go to read strings with the scanf
, even using the &
, he compiles?
Because C has weak typing. A lot weak.
For example:
char palavra[100];
char *ptr;
char **endereco;
ptr = palavra;
endereco = &ptr;
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 types.
endereco
, in turn, it’s another pointer. A pointer to a pointer. So it makes sense to assign endereco = &ptr
makes sense and respects typing.
However, C cannot differentiate in time from Runtime what types of variables. And at build level C treats pointers as pointers, regardless of which type is pointed. Of course, the compiler will complain, issue alerts (warnings in English), but if you had it done that way, you know.
C doesn’t care if you shoot yourself in the foot. The language assumes that the programmer knows what he is doing, so it will offer him no security against his own mistakes. If you are making monkey, the philosophy of language accept your monkey as law.
Patrick, @Maniero’s response is correct. There are conceptual errors in my response. I think it’s more appropriate to mark his response as the right one
– Jefferson Quesado