Dynamically allocate memory for Array of Structs

前端 未结 5 1664
北恋
北恋 2020-12-11 09:34

Here\'s what I\'m trying to do:

#include 
#include 

struct myStruct {
    int myVar;
}

struct myStruct myBigList = null;

vo         


        
相关标签:
5条回答
  • 2020-12-11 09:41

    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.

    0 讨论(0)
  • 2020-12-11 09:48
        sizeof(struct myStruct)
    

    or

        typedef struct myStruct myStrut;
        sizeof(myStruct)
    
    0 讨论(0)
  • 2020-12-11 09:58

    Shouldn't the following statement

    myArray[0].myVar = '42'; 
    

    be this?

    (*myArray)[0].myVar = 42;
    

    myvar is an integer.

    0 讨论(0)
  • 2020-12-11 10:00

    In order to work for all 10 elements for that array the line:

    myArray[0].myVar = '42';
    

    should be:

    (*myArray)[0].myVar = '42';
    
    0 讨论(0)
  • 2020-12-11 10:01

    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

    0 讨论(0)
提交回复
热议问题