>cc*****@yahoo.com wrote:
Is it possible to initialize the array without declaring
an intermediate variable to get an address?
In article <d3**********@news1brm.Central.Sun.COM>
Eric Sosman <er*********@sun.com> wrote: (See up-thread for snipped context: He wants to initialize
an array of pointers to structs that are also initialized.)
No. The string literal is the only C construct that
creates and initializes an "anonymous" object. All other
initialized objects must have names.
Except in C99, where compound literals create anonymous
objects.
For instance, in C99 (but not C89), one can write:
/* tables for decoding SCSI <code,subcode> pairs */
struct subcode {
int sc_num;
char *sc_msg;
};
struct code {
int co_num;
size_t co_nsub;
struct subcode *co_subc;
};
struct code scsi_codetab[] = {
{
0, 2,
(struct subcode [2]) {
{ 0, "0/0" },
{ 1, "0/1" },
},
},
{
1, 3,
(struct subcode [3]) {
{ 0, "1/0" },
{ 27, "1/27" },
{ 40, "1/40" },
}
},
};
(The above is not intended to be particularly useful; in particular
the code and subcode numbers are made up and the sc_msg strings are
ridiculous. But SCSI does have code/subcode pairs and the overall
technique itself is reasonable.)
Note that even though you *can* do this in C99, it is probably
better to use C89 constructs to match up the "number of subcodes"
initializer (for co_nsub) and actual table sizes automatically.
That is, writing this out "longhand" is actually less fragile:
struct subcode {
int sc_num;
char *sc_msg;
};
struct code {
int co_num;
size_t co_nsub;
struct subcode *co_subc;
};
static struct subcode sc0_table[] = {
{ 0, "0/0" },
{ 1, "0/1" },
};
static struct subcode sc1_table[] = {
{ 0, "1/0" },
{ 27, "1/27" },
{ 40, "1/40" },
};
#define COUNT_AND_TABLE(x) sizeof x / sizeof x[0], x
struct code scsi_codetab[] = {
{ 0, COUNT_AND_TABLE(sc0_table) },
{ 1, COUNT_AND_TABLE(sc1_table) },
};
There is in fact a more general rule of programming that applies
here: "if something is complex, give it a name."
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.