[英]How to initialize a pointer to a struct in 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
時,這不起作用,我假設我需要使用運算符->
進行初始化,但是如何?
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
如果復合文字出現在函數主體之外,則對象具有靜態存儲持續時間; 否則,它具有與封閉塊關聯的自動存儲時間。
是否可以聲明一個指向結構的指針並對其進行初始化?
是。
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;
首先,您需要為指針分配內存,如下所示:
myPipe = malloc(sizeof(struct PipeShm));
然后,您應該按如下所示逐一分配值:
myPipe->init = 0;
myPipe->flag = FALSE;
....
請注意,對於結構中的每個單獨的指針,您需要單獨分配內存。
好吧,我明白了:
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;
首先初始化結構( static struct PipeShm myPipe = {...
)。 然后取地址
struct PipeShm * pMyPipe = &myPipe;
您必須手動構建該結構,然后創建指向該結構的指針。
要么
static struct PipeShm myPipe ={};
static struct PipeShm *pmyPipe = &myPipe;
要么
static struct PipeShm *myPipe = malloc();
myPipe->field = value;
static struct PipeShm * myPipe = &(struct PipeShm) {.init = 0 , .flag = FALSE , .mutex = NULL ,
.ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 ,
.semaphoreFlag = FALSE };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.