30

鉴于此结构:

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 };

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

4

6 回答 6

55

你可以这样做:

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

此功能称为“复合文字”,它应该适合您,因为您已经在使用 C99 指定的初始化程序。


关于复合文字的存储:

6.5.2.5-5

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

于 2012-07-29T14:22:03.963 回答
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;
于 2012-07-29T14:22:00.913 回答
4

好的,我明白了:

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;
于 2012-07-29T14:22:09.407 回答
2

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

myPipe = malloc(sizeof(struct PipeShm));

然后,您应该如下一一分配值:

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

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

于 2012-07-29T14:21:05.377 回答
1

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

struct PipeShm * pMyPipe = &myPipe;
于 2012-07-29T14:21:52.157 回答
0

您必须手动构建该结构,然后创建一个指向该结构的指针。

任何一个

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

或者

static struct PipeShm *myPipe = malloc();
myPipe->field = value;
于 2012-07-29T14:24:32.323 回答