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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With