Search This Blog

Wednesday, September 9, 2009

Another method of initializing struct

A simple way to initialize the struct, which you will often encounter in Linux Kernel is :

Consider a struct :
struct temp {
int a;
int b;
};

To initialize the struct,
struct temp try = {.a = 2};
struct temp try1 = {.a = 3, .b =4};
struct temp try2 = {.a=4,};

All are valid initializations.

Imp!! However, this is allowed only for initialization while declaration, not later.

i.e. struct temp try;
try = {.a=2,.b=3};
is not allowed

1 comments:

mpol said...

you can do this in the middle of the code:

...
try = (struct temp){.a = 1, .b = 3};


I'm not sure if it is pretty or ugly, but works.

Post a Comment