How to allocate a member of a struct in C?

6

I would like to know if it is possible to allocate a atributo of a struct , follow my struct example:

struct MinhaStructExemplo
{
   int * atributo_quantidade; /*Atributo que eu gostaria de alocar na memoria*/
};
For the atributo_quantidade attribute I'd like to allocate the positions to it in memory using malloc , as if it were a pointer, follow what I've already tried:

#include <stdio.h>
#include <stdlib.h>

struct MinhaStructExemplo
{
    int  * atributo_quantidade; /*Atributo que eu gostaria de alocar na memoria*/
};

int main(void)
{
    int * valor;
    struct MinhaStructExemplo structExemplo;
    valor = malloc(sizeof(int) * 1);
    structExemplo.atributo_quantidade = malloc(sizeof(int) * 1);
}
    
asked by anonymous 27.11.2015 / 00:35

1 answer

5

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 .     

27.11.2015 / 01:20