C

Doug Gwyn gwyn at smoke.BRL.MIL
Wed Mar 1 15:25:03 AEST 1989


In article <9501 at bloom-beacon.MIT.EDU> yphotons at athena.mit.edu (Sun Warrior) writes:
>I would like to know how to set an array (float) to a certain size
>normally I would have done it like this
>float array [size]
>but the thing is I would first like to be able to type in the size and
>then set the array . I tried this by using scanf statement and then
>the float but that did not work. help

There must be some conceptual confusion here, because "setting the
size of an array" is not a C concept.
	float array[N];
declares that the name "array" denotes an array of N contiguous elements,
each element of type float.  The dimension N is used only to allocate
sufficient storage for N elements; you don't have to actually use them
all.  Thus one solution is to simply declare the array larger than you'll
ever need it to be, and keep track of the presumed valid size in a
separate integer variable (use that for loop limits, etc. in the code).
C does not permit N to be a variable in an array declaration; it must be
an integer constant [expression].

You can also obtain a pointer to storage sufficiently large to hold N
contiguous `float' elements via a call to the malloc() function:
	extern char *malloc();	/* void* for ANSI C */
	float *arrayp = (float *)malloc( N * sizeof(float) );
Here, N can be and often is a variable determined at run time.  In this
example, "arrayp" is NOT an array of N floats, but can be treated as
a pointer to the first member of such an array; therefore "arrayp"
can be used in most of the same contexts as those in which "array" might
have been used ("sizeof array" being the most notable exception).  That's
because C converts the name of an array "array" into a pointer to its
first element (similar to "arrayp") when it is used in most expressions.
Thus, "arrayp[i]" acts just like "array[i]" (it is the i+1st float in the
array; remember that C indexing starts at 0, not 1).



More information about the Comp.lang.c mailing list