In his statement:
pessoa* alocarEspaco(pessoa p, int tam)
It’s not necessary pessoa p
because the method will already allocate do the memory allocation. And when using size to count or allocate memory, choose to use unsigned
in the description as the unsigned
makes all the values you place become positive (It is more a form of organization). Thus leaving your method as follows:
pessoa* alocarEspaco(unsigned int tam)
In order to be able to allocate memory in a variable, it needs to be a pointer, and for that, it needs to *
(asterisk) in the declaration.
pessoa *ptr; // essa variável é um ponteiro por que tem um "*" na declaração
ptr = (pessoa *) malloc(sizeof(pessoa)*tam);
return ptr;
Now, the variable that will receive the value, must be a pointer as well.
pessoa *var = alocarEspaco(10); // aloca 10 pessoas em var
And now the part where a lot of people get confused.
How to pick up the pointer positions?
When the pointer has 1 space is used ->
. Ex:
pessoa *uma_pessoa = alocarEspaco(1);
uma_pessoa->idade = 10;
uma_pessoa->nome = "Fulano";
But of course this is for when the pointer has just 1 space. When multiple spaces are used .
(point). Ex:
pessoa *muitas_pessoas = alocarEspaco(10);
muitas_pessoas[0].nome = "Ciclano";
muitas_pessoas[1].nome = "Dertrano";
/*...*/
Because that?
Because when you take a position using [n]
, you are already accessing the memory address. So if your pointer has a position you can use the ->
, and if you have positions, you should use the [n]
(number in the cushions).
Thanks my brothers, I investigated a little more and already solved. I only had to declare the function in the prototypes
– Samuel Bié