如何在C中初始化指向结构的指针? [英] How to initialize a pointer to a struct in C?

查看:28
本文介绍了如何在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 };

但是当我声明 static struct PipeShm * myPipe 时,这不起作用,我假设我需要使用运算符进行初始化 ->,但如何?

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

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

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.

关于复合字面量的存储:

Regarding the storage of compound literals:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆