Why doesn't this work?
Tim Olson
tim at crackle.amd.com
Fri Mar 24 03:31:28 AEST 1989
In article <1309 at dukeac.UUCP> sbigham at dukeac.UUCP (Scott Bigham) writes:
| My annual C question:
|
| Is there a particularly glaring reason that the following code should make the
| compiler unhappy?
|
| ------------------- Quick, Robin! The BAT-scissors! -------------------
|
| typedef char **Block;
|
| Block
| b1 ={"this","that"},
| b2={"yes","no"},
| B[]={b1,b2};
| -------------------------------------------------------------------------
Unfortunately, there are no anonomous arrays in C, except for strings.
You are attempting to create anonomous arrays of character pointers
and assign their addresses to the variables b1 and b2. There are a
couple of ways to do what you want:
If b1 and b2 will always point to the initialized contents, then you
should declare them as:
typedef char *Static_Block[];
Static_Block
b1 = {"this, "that"},
.
.
If b1 and b2 may point to other data in the future, then you must give a
name to the initialized array contents:
typedef char **Block;
typedef char *Static_Block[];
Static_Block
init1 = {"this", "that"},
init2 = {"yes", "no"};
Block
b1 = init1,
b2 = init2;
________________________________________
That addresses your first problem. Your second problem is the
declaration:
Block
B[] = {b1, b2};
Here you are violating the requirement that initialization values must
be constants. I'm not quite sure what you are trying to do with the
array B. If you simply want it to hold the same *initial* contents as
b1 and b2, then you can use:
Block
B[] = {init1, init2};
If you want B to "track" the changing values of b1 and b2, then you have
to use one more level of indirection:
Block
*B[] = {&b1, &b2};
The addresses of b1 and b2 are constants, so they can be used in the
initialization.
--
-- Tim Olson
Advanced Micro Devices
(tim at amd.com)
-- Tim Olson
Advanced Micro Devices
(tim at amd.com)
More information about the Comp.lang.c
mailing list