Structure memory allocation in C

Does the distribution of an instance structusing mallocaffect the distribution of its members? That means doing something like this:

typedef struct { int *i; } test;
int main() {
     test *t = malloc(sizeof(test));
     t->i = malloc(sizeof(int));
}

... doesn't make sense because it ishould already be on the heap, right?

Or, is the structure simply conceptual to help a group of programmers two completely separate variables floating in memory? This means that: test *t = malloc(sizeof(test))just allocates memory to store pointers to items on the heap?

I am pretty puzzled by this.

+4
source share
4 answers

"test" struct malloc(sizeof(test)) , . , , :

typedef struct {
    char *string;
    char array[8];
} test;

, , , .

, struct : , .

+1

i test int, malloc ing test . malloc i , int.

EDIT:
, , . struct , malloc struct , , . malloc (, test->i = malloc (sizeof (int))).

+4

i, int. . :

#include <stdlib.h>

typedef struct
{
        int i;
} test;

typedef struct
{
        int* i; 
} testp;

int main()
{
        test* foo = malloc(sizeof(*foo));
        foo->i = 3;

        testp* bar = malloc(sizeof(*bar));
        bar->i = malloc(sizeof(*bar->i));
        *bar->i = 3;
}

, int i .

+1

When you call the first malloc, there is enough memory to hold the entire structure, including "* i", which has enough space to hold a pointer to an integer. However, the * I field remains uninitialized! therefore, you should not use * i before assigning it with a second malloc, which reserves memory for an integer.

+1
source

All Articles