Search code examples
cstructinstance

How to create a new instance of a struct


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;
};

I've seen two ways..

The first way (xCode says this is redefining the struct and wrong):

struct listitem* newItem = malloc(sizeof(struct listitem));

The second way:

listitem* newItem = malloc(sizeof(listitem));

Alternatively, is there another way?


Solution

  • 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));