You are trying to allocate a array with the size of the pointer to the date struct instead of the actual size of the date struct.

Change date* to date:

array = malloc(size*sizeof(date));

Furthermore you don't need to allocate the day and year variables, because the malloc allocates them for you.

for (i=0; i<size; i++)
{
     array[i].month = calloc(MAX_MONTH_STR,sizeof(char));
     array[i].day = 0;
     array[i].year = 0;
}
Answer from user1350184 on Stack Overflow
Discussions

Best practice on allocating memory for a struct that has dynamic array members
Right now, the for loop is always printing the same value. You also need to free(ms->my_arr); Every malloc will have a corresponding free. More on reddit.com
🌐 r/C_Programming
21
3
February 29, 2024
c - Need help allocating memory for an struct array of arrays - Stack Overflow
When you create an array of structs like this it's called static allocation so there's no need to call malloc at all. Just declaring the array allocates the memory for the structs. More on stackoverflow.com
🌐 stackoverflow.com
Correct way to allocate memory for struct with variable struct array?
board->fields is an array of pointers, which don't yet point anywhere. Did you intend struct game_board_bitmap fields[]; instead? More on reddit.com
🌐 r/C_Programming
6
2
February 22, 2022
c - Allocating memory for array of structs - Stack Overflow
I tried to initialize one at a ... is, how do I allocate memory of this kind and how can I access it later? Thank you in advance, and sorry for any typo. ... With char *name[200]; you can have 200 distinct strings in each struct (like you described, an array of strin... More on stackoverflow.com
🌐 stackoverflow.com
March 16, 2014
🌐
Reddit
reddit.com › r/c_programming › best practice on allocating memory for a struct that has dynamic array members
r/C_Programming on Reddit: Best practice on allocating memory for a struct that has dynamic array members
February 29, 2024 -

Hi all! I am very new to C but am familiar with Python & Go quite a bit. Memory allocation is a new concept to me, but I want to start with best practices.

Lets say I want to create a struct that has some members, where one of them happens to be a pointer which I will size dynamically as an array.

Here is what I am doing in my init_my_struct(int n) function. I want to understand if I am doing something that is bad practice here

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

struct my_struct {
        int n;
        int *my_arr; // this will be dynamically grown based on user arg
};

struct my_struct * init_my_struct(int n)
{
        // allocate memory for one struct
        struct my_struct *ms = malloc(sizeof(struct my_struct));
        
        // use -> syntax since ms is a pointer
        ms->n = n;
        ms->my_arr = malloc(sizeof(int)*n);
        return ms;
}

int main(int argc, char *argv[])
{
        if (argc < 2) return 1;

        int n = atoi(argv[1]);
        
        // initialize the struct members
        struct my_struct *ms = init_my_struct(n);
        
        // check out contents of my struct
        printf("my struct's n: %d\n", ms->n);
        printf("my struct's my_arr: \n");
        for (int i = 0; i < n; i++) {
                printf("%d\n", ms->my_arr[i]);
        }
        free(ms); // clean up the memory

        return 0;
}

Any pointers or tips would be great! Thank you!

🌐
Quora
quora.com › How-do-we-allocate-memory-for-a-structure-and-array-in-C
How do we allocate memory for a structure and array in C? - Quora
Answer (1 of 3): The exact size of array is unknown until the compile time,i.e., time when a compiler compiles code written in a programming language into a executable form. The size of array you have declared initially can be sometimes insufficient and sometimes more than required. Dynamic memor...
Find elsewhere
🌐
Reddit
reddit.com › r/c_programming › correct way to allocate memory for struct with variable struct array?
r/C_Programming on Reddit: Correct way to allocate memory for struct with variable struct array?
February 22, 2022 -

Hi,

currently I'm train my C skills (or get some in general, lol) and make a little training project: classical tic tac toe. I will "overcomplicate" the project on purpose with the intention to use many language skills as possible.

I will represent the "board" with this two structures:

struct game_board_bitmap {
    char player: 2;
};

struct game_board {
    unsigned int width;
    unsigned int height;
    unsigned int size;
    struct game_board_bitmap* fields[];
};

A classic board has a width and height of 3, so a size of 9. Every field should be represented with the struct game_board_bitmap and saved in a variable array in the struct game_board.

The purpose of the shown structure is to train the correct handling of malloc, free etc.

And this is also where I reach my limits. How do I create this nested structure correctly? I have tried it via the following way:

struct game_board* tictactoe_init_game_board(unsigned int const width, unsigned int const height) {
    struct game_board* board = malloc(sizeof(struct game_board) + (width * height) * sizeof(struct game_board_bitmap));

    // malloc test removed for space savings

    board->width = width;
    board->height = height;
    board->size = width * height;

    for (int i = 0; i < board->size; i++) {
        board->fields[i]->player = 0; // 0 is default, field not assigned to any player
    }

    return board;
}

If I want access the board via printf("%c", board->fields[2]->player); the program crashes with a SIGSEGV. So I think I have done something wrong.

Can someone please explain to me what exactly I am doing wrong or how to do it right? Thank you! :)

🌐
Cprogramming
cboard.cprogramming.com › c-programming › 144084-allocating-memory-array-structures.html
Allocating memory for array of structures - C Board
December 5, 2011 - 500 of them will occupy at least 105k of memory ... add in all your other arrays and it's very likely you've overflowed your program's stack... It happens rather often actually. The answer is to use malloc... ... struct data *array = malloc(number * sizeof(data)); This will allocate your arrays ...
🌐
Stack Overflow
stackoverflow.com › questions › 22435732 › allocating-memory-for-array-of-structs
c - Allocating memory for array of structs - Stack Overflow
March 16, 2014 - My question is, how do I allocate memory of this kind and how can I access it later? Thank you in advance, and sorry for any typo. ... With char *name[200]; you can have 200 distinct strings in each struct (like you described, an array of strings).
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › structs.html
2.7. C Structs
The semantics of passing classroom1 ... allocated) array to a function: the parameter refers to the same set of elements as the argument, and thus changes to the array’s values within the function affect the argument’s elements. Figure 3 shows what the stack might look like for the second call to the updateAges function (showing the passed classroom2 array with example field values for the struct in each of its elements). Figure 3. The memory layout of ...
🌐
Quora
quora.com › How-do-you-dynamically-allocate-an-array-of-struct-pointers-in-C
How to dynamically allocate an array of struct pointers in C - Quora
Answer (1 of 5): To dynamically allocate memory for pointer to array of struct you have to: * Create a pointer to pointer to the struct. * Then for example into a loop, allocate memory for any array member.
Top answer
1 of 2
37

Allocating works the same for all types. If you need to allocate an array of line structs, you do that with:

struct line* array = malloc(number_of_elements * sizeof(struct line));

In your code, you were allocating an array that had the appropriate size for line pointers, not for line structs. Also note that there is no reason to cast the return value of malloc().

Note that's it's better style to use:

sizeof(*array)

instead of:

sizeof(struct line)

The reason for this is that the allocation will still work as intended in case you change the type of array. In this case this is unlikely, but it's just a general thing worth getting used to.

Also note that it's possible to avoid having to repeat the word struct over and over again, by typedefing the struct:

typedef struct line
{
    char* addr;
    char* inst;
} line;

You can then just do:

line* array = malloc(number_of_elements * sizeof(*array));

Of course don't forget to also allocate memory for array.addr and array.inst.

2 of 2
10

For what you have described, You do not need to allocate memory for your struct, rather, you need to allocate memory for the members char *addr;, and char *inst;. If you want to have a single copy of that structure, the first section of code illustrates how to initialize, and assign values. If you want an array, the second code example illustrates the differences.

This illustrates how to allocate memory for the members of a single struct line:

typedef struct
{
    char* addr;
    char* inst;
}LINE;

LINE line;  

int main(void)
{   

    strcpy(line.addr, "anystring"); //will fail
    line.addr = malloc(80);
    line.inst = malloc(80);
    strcpy(line.addr, "someString");//success;
    strcpy(line.inst, "someOtherString");//success;

}

For array of struct line...

typedef struct
{
    char* addr;
    char* inst;
}LINE;  //same struct definition

LINE line[10]; //but create an array of line here.

int main(void)
{   
    int i;
    
    for(i=0;i<10;i++)
    {
      line[i].addr = malloc(80);
      line[i].inst = malloc(80);
    }

    for(i=0;i<10;i++)
    {
        strcpy(line[i].addr, "someString");
        strcpy(line[i].inst, "someOtherString");
    }
    //when done, free memory
    for(i=0;i<10;i++)
    {
        free(line[i].addr);
        free(line[i].inst);
    }      


}

Added to address comment
Addressing the comment under this answer from @Adam Liss, the following code illustrates the following improvements using strdup(): 1) Uses only memory needed. 2) Performs memory creation and copy operations in one step, so the the following blocks:

for(i=0;i<10;i++)
{
  line[i].addr = malloc(80);
  line[i].inst = malloc(80);
}

for(i=0;i<10;i++)
{
    strcpy(line[i].addr, "someString");
    strcpy(line[i].inst, "someOtherString");
}

Become:

for(i=0;i<10;i++)
{
  line[i].addr = strdup("someString");
  line[i].inst = strdup("someOtherString");
}

One more note: Error handling was not included in examples above to avoid muddling up focus on the main concepts: But for the sake of completeness, because both malloc() and strdup() can fail, actual usage for each of these two functions, should include a test before using, eg:

Rather than

  line[i].addr = strdup("someString");
  line[i].inst = strdup("someOtherString");

The code should include

  line[i].addr = strdup("someString");
  if(!line[i].addr)
  {
      //error handling code here
  }
  line[i].inst = strdup("someOtherString");
  if(!line[i].inst)
  {
      //error handling code here
  }
🌐
YouTube
youtube.com › watch
How to Dynamically Allocate Memory for an Array of Structs in C - YouTube
Learn how to effectively use `malloc` to dynamically allocate memory for an array of structs in C. Get insights on type casting and best practices for memory...
Published   May 26, 2025
Views   1
🌐
Quora
quora.com › How-do-I-malloc-an-array-of-structs-in-C
How to malloc() an array of structs in C - Quora
Then, [code]struct X *pArray = malloc(sizeof(struct X) * N); if (pArray) { // Access elements using pArray } [/code]It’s really that simple. You can use pArray with square bracket i...