How to initialize a pointer to a struct in C?

前端 未结 6 1879
礼貌的吻别
礼貌的吻别 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:01

    First you need to allocate memory for the pointer as below:

    myPipe = malloc(sizeof(struct PipeShm));
    

    Then, you should assign values one by one as below:

    myPipe->init = 0;
    myPipe->flag = FALSE;
    ....
    

    Please note that for each individual pointer inside the structure, you need allocate memory seperately.

提交回复
热议问题