Initializing a pointer inside a struct
Paul D. Smith
pds at lemming.webo.dg.com
Thu Apr 18 10:42:43 AEST 1991
[] On 17 Apr 91 10:51:39 GMT, f90angu at fy.chalmers.se (Andreas Gunnarsson) said:
AG> I've tried this:
AG> struct
AG> {
AG> ...
AG> int *int_list;
AG> ...
AG> } list_of_structs[] =
AG> {
AG> { ..., {1, 2, 3, -1}, ...},
AG> { ..., {4, -1}, ...},
AG> .
AG> .
AG> .
AG> };
AG> It doesn't work. I know I could declare the lists of integers as
AG> separate variables and use the address, but it would be much
AG> harder to see what data belongs where, and I would have to use
AG> *lots* of variable names. I could also write 'int int_list[MAX];'
AG> instead of 'int *int_list;', but in that case lots of space would
AG> be wasted if there is big variance in length.
You can't do it, because the types are different. The only exception
is a special case for strings, and you use "abcd" syntax instead of
{'a', 'b', 'c', 'd'}, so it's easy to see the special case.
Remember that a {1, 2, 3, 4} is an array of ints, with memory
allocated (i.e., array[4]). int *array is a pointer to an int, with
no memory allocated. C does not allow you to have the compiler
"infer" memory allocation for anything except strings, as above.
I would go with the same structure you have above (i.e., don't use
arrays), and declare the integers as seperate variables, as you
mentioned. True, it's harder to see the relationship. You can get
around the "lots of variable names" problem by making them all static
(yes, there are still lots but at least they don't exist beyond the
scope of the file).
I've written a couple of compilers as software development tools which
generate static initializations for complex structures, and have run
into this problem as well. The best you can do is declare them
seperately.
paul
-----
------------------------------------------------------------------
| Paul D. Smith | pds at lemming.webo.dg.com |
| Data General Corp. | |
| Network Services Development Division | "Pretty Damn S..." |
| Open Network Systems Development | |
------------------------------------------------------------------
More information about the Comp.lang.c
mailing list