gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:27:23 25 4
gpt4 key购买 nike

给定这个结构:

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/11709929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com