Dynamically allocate memory for Array of Structs

24,768

Solution 1

There are a few errors in your code. Make it:

struct myStruct *myBigList = NULL; /* Pointer, and upper-case NULL in C. */

/* Must accept pointer to pointer to change caller's variable. */
void defineMyList(struct myStruct **myArray)
{
     /* Avoid repeating the type name in sizeof. */
     *myArray = malloc(10 * sizeof **myArray);

     /* Access was wrong, must use member name inside structure. */
     (*myArray)[0].myVar = 42;
}

int main()
{
     defineMyList(&myBigList);
     return 0; /* added missing return */
}

Basically you must use the struct keyword unless you typedef it away, and the global variable myBigList had the wrong type.

Solution 2

This is because struct name is not automatically converted into a type name. In C (not C++) you have to explicitly typedef a type name.

Either use

struct myStruct instance;

when using the type name OR typedef it like this

typedef struct {
    int myVar;
} myStruct;

now myStruct can simply be used as a type name similar to int or any other type.

Note that this is only needed in C. C++ automatically typedefs each struct / class name.

A good convention when extending this to structs containing pointers to the same type is here

Solution 3

    sizeof(struct myStruct)

or

    typedef struct myStruct myStrut;
    sizeof(myStruct)
Share:
24,768
Mark Löwe
Author by

Mark Löwe

Updated on July 09, 2022

Comments

  • Mark Löwe
    Mark Löwe almost 2 years

    Here's what I'm trying to do:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct myStruct {
        int myVar;
    }
    
    struct myStruct myBigList = null;
    
    void defineMyList(struct myStruct *myArray)
    {
         myStruct *myArray = malloc(10 * sizeof(myStruct));
    
         *myArray[0] = '42';
    }
    
    int main()
    {
         defineMyList(&myBigList);
    }
    

    I'm writing a simple C program to accomplish this. I'm using the GNU99 Xcode 5.0.1 compiler. I've read many examples, and the compiler seems to disagree about where to use the struct tag. Using a struct reference inside the sizeof() command doesn't seem to recognize the struct at all.

  • fkl
    fkl over 10 years
    +1 for asking to avoid "struct" in sizeof and use the instance name instead.
  • Mark Löwe
    Mark Löwe over 10 years
    This worked great! Thank you! The ** was the key. Virtual drinks for everyone! Thanks again. All of you cleared up a lot of the confusion.
  • StarDust
    StarDust almost 7 years
    You should free myBigList inside main()
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 6 years
    '42' is not a normal character constant though!
  • Ilja Everilä
    Ilja Everilä over 6 years
    This seems like a comment on the accepted answer, not an answer to the question itself.
  • Ilja Everilä
    Ilja Everilä over 6 years
    This seems like a comment on the accepted answer, not an answer to the question itself.