Search code examples
cdata-structuresdynamic-memory-allocation

Allocating Memory for a Structure in C


I have done some research on allocating memory for a struct already on stackoverflow and the answers that i found did not work for me. With that said, here is my question and problem. For the most part a majority of them had the same bit of code that i currently have. Although my compiler is giving me an error.

Problem: I would like to allocate the memory for a Struct(an array of structs) and not a Pointer(pointer to a struct). Below is the definition of my Struct.

 #define INIT_MEMO_SIZE

typedef struct Memo
{
   struct HugeInteger *F; 
   int length; 

}Memo; 

Required Solution: Within memo struct i would like to dynamically allocate an array of INIT_MEMO_SIZE number of huge integer structs

Attempted Solution: below right at "malloc" I am getting an error stating "Error: An entity of type 'void *' cannot be used to initialize an entity of type 'HugeInteger *' this underlines the keyword "malloc" in red. Compiler being used is Microsoft Visual Studio 2012

// Creates and initializes a Memo Struct
Memo *createMemo(void)
{ 
    HugeInteger *ptr = malloc(sizeof(HugeInteger) * INIT_MEMO_SIZE); 

    if(ptr == NULL)
        return NULL; 

} // End of *createMemo

Question: What am i doing wrong or what is the proper way to allocate the array of structs?


Solution

  • malloc returns a void*. You need to cast the returned value.

     HugeInteger *ptr = (HugeInteger*)malloc(sizeof(HugeInteger) * INIT_MEMO_SIZE);