2

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...

Pedro Lima
  • 387
  • 2
  • 14

2 Answers2

3

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.

Chandra Shekhar
  • 598
  • 1
  • 7
  • 25
-1

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++

Simon Kuang
  • 3,870
  • 4
  • 27
  • 53
Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92
  • I think it's a bit misleading to say the ShortData array is on the stack, since OP is allocating the storage for the outer `struct postsTempo` with `malloc`. – Ian Abbott Apr 24 '18 at 15:24
  • In this case, would not ShortData be allocated on the heap because it is part of the struct that was allocated on the heap? Edit: I see someone has already commented on that. – Christian Gibbons Apr 24 '18 at 15:26