Pedro Lima
Pedro Lima

Reputation: 407

Malloc the elements of a struct

I have the following struct:

struct postsTempo {
    int ano;
    ShortData dias[373];
    struct postsTempo* prox;
};

When I do malloc(sizeof(struct postsTempo)) have I allocated everything that I need or do i still need to malloc the ShortData array? I cant add anything to that array...

Upvotes: 2

Views: 414

Answers (2)

Chandra Shekhar
Chandra Shekhar

Reputation: 617

Whenever you allocate memory using malloc() it creates the memory space for all variables declared inside the structure.

So there is no need to use malloc further for ShortData.

Upvotes: 3

Leo Chapiro
Leo Chapiro

Reputation: 13984

Yes, you don't need to malloc the ShortData array because this is a local array created on the stack, and has automatic storage duration. Take a look: Static array vs. dynamic array in C++

Upvotes: -1

Related Questions