如何初始化一个指针在C结构? [英] How to initialize a Pointer to a struct in 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 };
但是,当我宣布静态结构PipeShm * myPipe
,不工作,我假设我需要与运营商<$ C $初始化C> - &GT; ,但如何?
But when I declare static struct PipeShm * myPipe
, that doesn't work , I'm assuming that I'd need to initialize with the operator ->
, but how ? :
static struct PipeShm * myPipe = {.init = 0 , .flag = FALSE , .mutex = NULL , .ptr1 = NULL , .ptr2 = NULL ,
.status1 = -10 , .status2 = -10 , .semaphoreFlag = FALSE };
是否有可能一个指针声明一个struct并使用初始化呢?
Is it possible to declare a pointer to a struct and use initialization with it ?
推荐答案
您可以像这样:
static struct PipeShm * myPipe = &(struct PipeShm) {
.init = 0,
/* ... */
};
此功能被称为复合文字,它应该,因为你已经在使用C99指定初始化为你工作。
This feature is called a "compound literal" and it should work for you since you're already using C99 designated initializers.
关于复合文字的存储:
6.5.2.5-5
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结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!