Error: Conversion to non-scalar type requested

后端 未结 3 640
灰色年华
灰色年华 2021-02-04 05:04

I\'m having a small problem trying to malloc this struct. Here is the code for the structure:

typedef struct stats {                  
    int strength;                  


        
相关标签:
3条回答
  • 2021-02-04 05:30

    The memory assigned by malloc must be stored in a pointer to an object, not in the object itself:

    dungeon *d1 = malloc(sizeof(dungeon));
    
    0 讨论(0)
  • 2021-02-04 05:46

    malloc returns a pointer, so probably what you want is the following:

    dungeon* d1 = malloc(sizeof(dungeon));
    

    Here is what malloc looks like:

    void *malloc( size_t size );
    

    As you can see it return void*, however you shouldn't cast the return value.

    0 讨论(0)
  • 2021-02-04 05:48

    You can't cast anything to a structure type. What I presume you meant to write is:

    dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));
    

    But please don't cast the return value of malloc() in a C program.

    dungeon *d1 = malloc(sizeof(dungeon));
    

    Will work just fine and won't hide #include bugs from you.

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