c - C语言中如何初始化结构体指针?

标签 c pointers struct initialization

给定这个结构:

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/

相关文章:

c++ - 如何最好地将递归结构体的本地生成元素保留在内存中?

c - 学习 Unix 和 C — 查看进程、文件和 v 节点表

c - 如何使用源代码测量每个节点的 MPI 基准?

c++ - 将引用用作数组/指针是否合法?

c++ - 如何决定堆栈中的内容?

c - 当没有 IntelliSense 错误时,为什么会有这么多编译错误?怎么修?

go - 如何在Golang中使用 map 接口(interface)?

c - 将字符串重新排列成回文 C

c - 结构中 ‘:’ 标记之前出现错误 : expected ‘,’ , ‘;’、 ‘}’、 ‘__attribute__’ 或 ‘=’

c++ - 如何比较指针?