如何在C中初始化指向结构的指针?

鉴于此结构:

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

这工作正常:

 static struct PipeShm myPipe = { .init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE }; 

但是,当我声明static struct PipeShm * myPipe ,这不起作用,我假设我需要使用运算符初始化-> ,但是如何?

 static struct PipeShm * myPipe = {.init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE }; 

是否可以声明一个指向结构的指针并使用它进行初始化?

你可以这样做:

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

此function称为“复合文字”,它应该适用于您,因为您已经在使用C99指定的初始值设定项。


关于复合文字的存储:

6.5.2.5-5

如果复合文字出现在函数体外,则该对象具有静态存储持续时间; 否则,它具有与封闭块相关的自动存储持续时间。

是否可以声明一个指向结构的指针并使用它进行初始化?

是。

 const static struct PipeShm PIPE_DEFAULT = {.init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE }; static struct PipeShm * const myPipe = malloc(sizeof(struct PipeShm)); *myPipe = PIPE_DEFAULT; 

首先,您需要为指针分配内存,如下所示:

 myPipe = malloc(sizeof(struct PipeShm)); 

然后,您应该逐个分配值,如下所示:

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

请注意,对于结构中的每个单独指针,您需要单独分配内存。

好的,我明白了:

 static struct PipeShm myPipeSt = {.init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE }; static struct PipeShm * myPipe = &myPipeSt; 

首先初始化struct( static struct PipeShm myPipe = {... )。 然后拿地址

 struct PipeShm * pMyPipe = &myPipe; 

你必须手工构建该结构,然后制作指向该结构的指针。

 static struct PipeShm myPipe ={}; static struct PipeShm *pmyPipe = &myPipe; 

要么

 static struct PipeShm *myPipe = malloc(); myPipe->field = value;