This example should clarify better:
#include <stdio.h>
#include <stdlib.h>
struct MinhaStructExemplo {
int *atributo_quantidade;
};
int main(void) {
int *valor;
struct MinhaStructExemplo structExemplo;
valor = malloc(sizeof(int));
*valor = 10;
structExemplo.atributo_quantidade = valor;
printf("%d\n", *structExemplo.atributo_quantidade);
structExemplo.atributo_quantidade = malloc(sizeof(int));
*structExemplo.atributo_quantidade = 30;
printf("%d\n", *structExemplo.atributo_quantidade);
structExemplo.atributo_quantidade = malloc(sizeof(int) * 3);
structExemplo.atributo_quantidade[0] = 1;
structExemplo.atributo_quantidade[1] = 2;
structExemplo.atributo_quantidade[2] = 3;
printf("%d\n", structExemplo.atributo_quantidade[0]);
printf("%d\n", structExemplo.atributo_quantidade[1]);
printf("%d\n", structExemplo.atributo_quantidade[2]);
}
See running on ideone .
If you want to save the value of the valor
variable, simply place the contents of the variable in the member. Both are pointers. What is stored in the variable is the pointer (created by malloc
) and not value pointed to by it (done shortly thereafter). So when we want to point to the same place, that is, for the same value, just a direct assignment.
Then I made a new allocation in memory and with this new address was assigned to the structure member. Then a value was placed at this address.
Whenever a type is a pointer, it must contain a memory address that points to where it has a value. To obtain a memory address there are basically three options: 1) allocate memory with malloc
; 2) takes an address of an object with the &
operator; 3) copy an existing address into another variable (possibly can be a literal).
Then the same was done with a sequential allocation simulating an array .