Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a pointer to a struct in C?

Given this struct:

struct PipeShm {     int init;     int flag;     sem_t *mutex;     char * ptr1;     char * ptr2;     int status1;     int status2;     int semaphoreFlag;  }; 

That works fine:

static struct PipeShm myPipe = { .init = 0 , .flag = FALSE , .mutex = NULL ,          .ptr1 = NULL , .ptr2 = NULL , .status1 = -10 , .status2 = -10 ,          .semaphoreFlag = FALSE }; 

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?

like image 357
JAN Avatar asked Jul 29 '12 14:07

JAN


People also ask

How do you declare a pointer to a struct?

To declare a structure pointer struct keyword is used followed by the structure name and pointer name with an asterisk * symbol. Members of a structure can be accessed from pointers using two ways that are. Using dot and asterisk operator on a pointer.

Can we have a pointer to a struct?

As we know Pointer is a variable that stores the address of another variable of data types like int or float. Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures.


1 Answers

You can do it like so:

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

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.

like image 198
cnicutar Avatar answered Sep 17 '22 14:09

cnicutar