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

c - How to allocate memory and dereference an array of arrays within a struct? - Stack Overflow
I was wondering how I would access a double pointer inside of a struct, for example: typedef struct Example { char **set; int size; }Example; The struct is called inside the function as: ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - Need help allocating memory for an struct array of arrays - Stack Overflow
Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 0 How to properly allocate memory for structs, arrays of structs inside a struct, and passing that array as a parameter More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - How do I allocate memory for a struct with an array? - Stack Overflow
Suppose I have this struct representing a virtual machine. Please, check out my init() method. In the init() method I am allocating some space in the heap for the state of my virtual machine. But, 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
๐ŸŒ
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!

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 46386297 โ€บ how-to-allocate-memory-and-dereference-an-array-of-arrays-within-a-struct
c - How to allocate memory and dereference an array of arrays within a struct? - Stack Overflow
struct Example exmpl; exmpl.set = malloc(10 * sizeof(char*)); // 10 "arrays" in the set for (int i = 0; i < 10; i++) exmpl.set[i] = malloc(20 * sizeof(char)); // 20 chars within each "array" ... And, an array and a pointer are different, so what you have here is a pointer to a pointer to char (which works similarly to a 2-dimensional array of chars)
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ how-to-correctly-allocate-memory-for-an-array-of-structs-in-c
How to Allocate Memory for an Array of Structs in C: Complete 2026 Guide - Allocate memory for an array of structs in c complete
November 20, 2025 - Dynamic memory allocation for structs involves requesting heap memory at runtime using library functions from <stdlib.h>. The fundamental concept is simple: you allocate enough memory to hold one or more struct instances, receive a pointer to that memory, and can then access the struct fields ...
๐ŸŒ
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! :)

Find elsewhere
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
  }
๐ŸŒ
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...
๐ŸŒ
Diveintosystems
diveintosystems.org โ€บ book โ€บ C2-C_depth โ€บ structs.html
2.7. C Structs
Figure 1 sketches what the variables s and sptr may look like in memory after the code above executes. Recall that malloc allocates memory from the heap, and local variables are allocated on the stack. Figure 1. The differences in memory layout between a statically allocated struct (data on ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ c malloc struct
How to Allocate Struct Memory With malloc in C | Delft Stack
February 12, 2024 - This code defines a structure MyObject containing valid, data, and size members. It includes functions to initialize and deallocate an array of MyObject instances. In main, it dynamically allocates memory for an array of MyObject objects, initializes them, and then deallocates the memory to prevent memory leaks.
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 144084-allocating-memory-array-structures.html
Allocating memory for array of structures - C Board
December 5, 2011 - It happens rather often actually. The answer is to use malloc... ... struct data *array = malloc(number * sizeof(data)); This will allocate your arrays on the program's heap, placing only pointers on the stack.... so a 105k array can be replaced by an 8 byte pointer.
๐ŸŒ
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
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ c array of structs
How to Create Array of Structs in C | Delft Stack
February 12, 2024 - Here, ptrVariable is a pointer ... creating an array of structs, we determine the size by multiplying the number of elements by the size of each struct using sizeof....
Top answer
1 of 2
9

When you use realloc(), you must give the new size instead of the number of bytes to add. So:

temp_struct = (struct st_temp **) realloc (temp_struct, 30 * sizeof(struct st_temp*));

30 is, of course, your original 20 plus 10 more. The realloc() function takes care of copying the original data to a new location if it needs to move the memory block.

Then, adding the extra 10 elements would be something like (starting at index 20, not 0):

for (j = 20; j < 30; j++) {
    temp_struct[j]->prod = "some extra values"; 
}
2 of 2
7

To avoid memory leaks, we need to handle reallocating with care (more on that later). The realloc function:

void *realloc(void *ptr, size_t size), where

ptr = the pointer to the original (malloc'ed) memory block, and

size = the new size of the memory block (in bytes).

realloc returns the new location of the dynamically allocated memory block (which may have changed) - or NULL if the re-allocation failed! If it returns NULL, the original memory stays unchanged, so you must always use a temporary variable for the return value of realloc.

An example will clarify this a bit (points of interest: realloc syntax is similar to malloc's (no need for extra casts etc.) and, after realloc, you need to produce the same steps for the new objects as you did after malloc):

struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { /* handle failed malloc */ }
for (int i = 0; i < 20; ++i) {
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "foo";
}

// We need more space ... remember to use a temporary variable
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) { 
    // handle failed realloc, temp_struct is unchanged
} else {
    // everything went ok, update the original pointer (temp_struct)
    temp_struct = tmp; 
}
for (int i = 20; i < 30; ++i) { // notice the indexing, [20..30)
    // NOTICE: the realloc allocated more space for pointers
    // we still need to allocate space for each new object
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "bar";
}
// temp_struct now "holds" 30 temp_struct objects
// ...
// and always do remember, in the end
for (int i = 0; i < 30; ++i)
    free(temp_struct[i]);
free(temp_struct);

Do note, that this is not really an array of structs, but more an array of pointers to structs - or even an array of arrays of struct if you wish. In the last case, each sub-array would be of length 1 (since we only allocate space for one struct).