Search code examples
cstructinitializationdesignated-initializer

How To Initialize a C Struct using a Struct Pointer and Designated Initialization


How can I use struct pointers with designated initialization? For example, I know how to init the struct using the dot operator and designated initialization like:

person per = { .x = 10,.y = 10 };

But If I want to do it with struct pointer?

I made this but it didn't work:

    pper = (pperson*){10,5};

Solution

  • You can use a pointer to a compound literal:

    struct NODE{
       int x;
       int y;
    }
    
    
    struct NODE *nodePtr = &(struct NODE) {
        .x = 20,
        .y = 10
    };
    
    • Notice that compund literals were introduced in C99.