0

Possible Duplicate:
How to initialize a struct in ANSI C

I have a global variables in my code with initial values , which are :

int init = 0;
int flag = FALSE;
sem_t *mutex;
char * ptr1 = NULL;
char * ptr2 = NULL;
int status1 = -10;
int status2 = -10;
int semaphoreFlag = FALSE;

Instead , I decided to add a struct :

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

However ,I can't set initial values to the struct's fields , like I did when the variables are global variables .

I guess that the usual way would be to have a void init() method that would set the values of the struct to the requested values ... but I'm looking for something else ... Any way around this ?

Thanks

0

1 Answer 1

1

In addition to @DCoder's suggested solution, you can also instanciate and initialize a variable with that structure as follow:

struct PipeShm
{
    int init;
    int flag;
    sem_t *mutex;
    char * ptr1;
    char * ptr2;
    int status1;
    int status2;
    int semaphoreFlag;
} defaults = {
    .init = 0,
    .flag = 0,
    .mutex = NULL,
    .ptr1 = NULL,
    .ptr2 = NULL,
    .status1 = 0,
    .status2 = 0,
    .semaphoreFlag = 0
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.