How to initialize a pointer to a struct in C?

前端 未结 6 1871
礼貌的吻别
礼貌的吻别 2020-12-02 17:27

Given this struct:

struct PipeShm
{
    int init;
    int flag;
    sem_t *mutex;
    char * ptr1;
    char * ptr2;
    int status1;
    int status2;
    in         


        
6条回答
  •  借酒劲吻你
    2020-12-02 18:14

    You can do it like so:

    static struct PipeShm * myPipe = &(struct PipeShm) {
        .init = 0,
        /* ... */
    };
    

    This feature is called a "compound literal" and it should work for you since you're already using C99 designated initializers.


    Regarding the storage of compound literals:

    6.5.2.5-5

    If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

提交回复
热议问题