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

Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318

1 Answers1

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
};
Aif
  • 11,015
  • 1
  • 30
  • 44