Initializing a pointer inside a struct

Stephen Clamage steve at taumet.com
Thu Apr 25 01:06:46 AEST 1991


pds at lemming.webo.dg.com (Paul D. Smith) writes:

>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.

These comments are simply incorrect.  The notation {1, 2, 3, 4} is
used to initialize a declared aggregate.  It is not, and does not
represent, an array, although it can be used to initialize one.
For example:
	int i1[4] = {1, 2, 3, 4};
	long l2[] = {1, 2, 3, 4};
	struct s { int a, b, c, d; } s1 = {1, 2, 3, 4};
	struct t { float x[2]; short y; char z; } = {1, 2, 3, 4};

C does allow the compiler to "infer memory allocation", as in the second
example line.  The size of array l2 is determined by the compiler based
on the number of initializers supplied, and the compiler allocates that
much space for it.  This array is not a "string", which usually means
"array of char".  (The last example is legal, but not recommended style,
as the initialization is not "fully bracketed".  It is better style to
write it as {{1, 2}, 3, 4}, or better still, {{1.0f, 2.0f}, 3, 4}, but
the example as shown is legal.)
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list