In your statement:
pessoa* alocarEspaco(pessoa p, int tam)
% is not required because the method will already allocate memory allocation. And when using size to count or allocate memory, opt to use pessoa p
in the description, because unsigned
causes all values that you put to become positive (It's more a form of organization). So leaving your method as follows:
pessoa* alocarEspaco(unsigned int tam)
In order to allocate memory in a variable, it needs to be a pointer, and for that, it is necessary to place a unsigned
(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 is to receive the value must be a pointer as well.
pessoa *var = alocarEspaco(10); // aloca 10 pessoas em var
And now the part that a lot of people make confusing.
How to get pointer positions?
When the pointer has 1 space it uses *
. Ex:
pessoa *uma_pessoa = alocarEspaco(1);
uma_pessoa->idade = 10;
uma_pessoa->nome = "Fulano";
But of course this is for when the pointer has only 1 space. When you have multiple spaces, use ->
(dot). Ex:
pessoa *muitas_pessoas = alocarEspaco(10);
muitas_pessoas[0].nome = "Ciclano";
muitas_pessoas[1].nome = "Dertrano";
/*...*/
Why this?
Because when you take a position using .
, you are already accessing the memory address. So if your pointer has a position you can use [n]
, and if you have several positions, you should use ->
(number on the links).