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

uyhoqukh  于 2022-12-17  发布在  其他
关注(0)|答案(7)|浏览(175)

给定以下结构:

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

是否可以声明一个指向结构体的指针并对它使用初始化?

3htmauhk

3htmauhk1#

你可以这样做:

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

这个特性被称为“复合字面量”,它应该对你有用,因为你已经在使用C99指定的初始化器了。
关于复合文字的存储:
6.5.2.5-5
如果复合文本出现在函数体之外,则对象具有静态存储持续时间;否则,它具有与封闭块相关联的自动存储持续时间。

cngwdvgl

cngwdvgl2#

是否可以声明一个指向结构体的指针并对它使用初始化?
是的。

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;
6qqygrtg

6qqygrtg3#

好的我知道了

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

lh80um4z4#

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

myPipe = malloc(sizeof(struct PipeShm));

然后,您应按如下方式逐一赋值:

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

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

jv2fixgn

jv2fixgn5#

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

struct PipeShm * pMyPipe = &myPipe;
gwbalxhn

gwbalxhn6#

你必须手工构建这个结构体,然后创建一个指向它的指针
或者

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

static struct PipeShm *myPipe = malloc();
myPipe->field = value;
shyt4zoc

shyt4zoc7#

静态结构体PipeShm * myPipe = &(结构体PipeShm){.初始化= 0,.标志=假,.互斥体=空,. ptr 1 =空,. ptr 2 =空,.状态1 = -10,.状态2 = -10,.信号量标志=假};

相关问题