给定这个结构:
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,
/* ... */
};
此功能称为“复合文字”,它应该适合您,因为您已经在使用 C99 指定的初始值设定项。
<小时/>关于复合文字的存储:
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.
关于c - C语言中如何初始化结构体指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57462871/