Path: utzoo!attcan!uunet!aplcen!samsung!cs.utexas.edu!radar!cadillac!vaughan@mcc.com From: vaughan@mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: Re: initializing a struct (or any class) array Keywords: struct initialization Message-ID: <12135@cadillac.CAD.MCC.COM> Date: 15 Oct 90 16:35:35 GMT References: <2840@unccvax.uncc.edu> <4596@sage.cc.purdue.edu> Sender: news@cadillac.CAD.MCC.COM Reply-To: vaughan@mcc.com (Paul Vaughan) Organization: MCC VLSI CAD Program Lines: 71 In-reply-to: rusbara2@sage.cc.purdue.edu (Bob Rusbasan) From: rusbara2@sage.cc.purdue.edu (Bob Rusbasan) In article <2840@unccvax.uncc.edu> cs00jec@unccvax.uncc.edu (Jim Cain) writes: > >I am trying to define a structure array for a static set of data. In C I >would declare the following: [ example of typical structure initialization deleted ] >This will be used by a parser as a look-up table for command names and >other information which belongs to each command. >This is identical to C code I have written that works. My question is -- >Is something this simple possible in C++? It seems that C++ considers >structs and unions as classes. Can you initialize class object arrays >like this? I really don't want the overhead of using pointers (such as >a linked list representation) because there is no reason for this data >to be dynamic (unless, of course, that's the only way to do it). I remember having tons of fun when I first tried to do this. What would be nice is if you could do this . . . Anyway, here's what you have to do (unless I missed something; Lord knows I tried, and this does work): foo name[] = { foo ( 0, 5, "name"), foo ( 7, 4, "another_name" ) foo [ ... ] }; Bob gave a reasonable answer, but seems to have missed that the original code posted by Jim also works fine (and is simpler to some people's minds). #include struct { char *name; int i; } list [] = { "namezero", 5, "nameone", 1, "namen", 16 }; main() { for(int i = 0; i < 3; i++) cout << list[i].name << " " << list[i].i << "\n"; } bash$ !g g++ -o trash trash.cc bash$ trash namezero 5 nameone 1 namen 16 bash$ !C CC -o trash trash.cc CC trash.cc: cc -o /d2/prism/prism/src/sim/src/trash -I/net/sunspot/usr/cadsw/CC/sun4/incl trash.c -L/net/sunspot/usr/cadsw/CC/sun4/ -lC bash$ trash namezero 5 nameone 1 namen 16 Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan