How to create a new instance of a struct

后端 未结 3 441
独厮守ぢ
独厮守ぢ 2021-01-01 16:50

What is the correct way to create a new instance of a struct? Given the struct:

struct listitem {
    int val;
    char * def;
    struct listitem * next;
};
         


        
相关标签:
3条回答
  • 2021-01-01 17:02

    The second way only works if you used

    typedef struct listitem listitem;
    

    before any declaration of a variable with type listitem. You can also just statically allocate the structure rather than dynamically allocating it:

    struct listitem newItem;
    

    The way you've demonstrated is like doing the following for every int you want to create:

    int *myInt = malloc(sizeof(int));
    
    0 讨论(0)
  • 2021-01-01 17:25
    struct listitem newItem; // Automatic allocation
    newItem.val = 5;
    

    Here's a quick rundown on structs: http://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm

    0 讨论(0)
  • 2021-01-01 17:27

    It depends if you want a pointer or not.

    It's better to call your structure like this :

    typedef struct s_data 
    {
        int a;
        char *b;
        // etc..
    } t_data;
    

    After to instanciate it for a no-pointer structure :

    t_data my_struct;
    my_struct.a = 8;
    

    And if you want a pointer you need to malloc it like that :

    t_data *my_struct;
    my_struct = malloc(sizeof(t_data));
    my_struct->a = 8
    

    I hope this answers your question.

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