[comp.lang.c] How to do run-time array declaration?

c60c-4br@e260-3a.berkeley.edu (09/20/88)

Can any one tell me if there is any trick for run-time declaration of
arrays?  What I want to do is to read in the actual array size from a
file at runtime (so the size depends on the file read in), then
proceed to define the array.  I heard you can get the space by using
calloc(), but then will you be able to treat it as array?  Please
e-mail me if you have any suggestions, thanks in advance.




-------------------------------------------------------------------
Jerry Yao				"LIVE SYMBOLICALLY!!"
c60c-4br@rosebud.berkeley.Edu

chris@mimsy.UUCP (Chris Torek) (09/21/88)

In article <14502@agate.BERKELEY.EDU> c60c-4br@e260-3a.berkeley.edu writes:
>Can any one tell me if there is any trick for run-time declaration of
>arrays?  What I want to do is to read in the actual array size from a
>file at runtime (so the size depends on the file read in), then
>proceed to define the array.

You cannot do this in C.  C arrays have a fixed size at compile time.

>I heard you can get the space by using calloc(), but then will you be
>able to treat it as array?

What you can do is simple, if somewhat limited.  The C language assumes
a `locally flat' address space: any single object has a contiguous address
space, and a pointer that points somewhere within such an object may be
used (with pointer arithmetic) to refer to other parts of that object.

Specifically, you can allocate a blob of memory and call it `an array',
and keep a pointer into that array (typically pointing to the beginning):

	#include <stddef.h>

	typedef int data_t;

	f() {
		data_t *p; int i, n;

		n = get_size();
		p = malloc(n * sizeof(*p));
		/* or p = calloc(n, sizeof *p) */
		/* or p = (data_t *)... in `old C' */
		if (p == NULL) ... handle error ...

		for (i = 0; i < n; i++)
			p[i] = value;
	}

You cannot, however, do this (except in `extended' C compilers):

	f() {
		int n = get_size();

		f1(n);
	}

	f1(int n) {
		data_t p[n];
		int i;

		for (i = 0; i < n; i++)
			p[i] = value;
	}

Note that GCC accepts the latter, and does the obvious thing, but
this is not part of the draft standard C.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

chris@mimsy.UUCP (Chris Torek) (09/21/88)

In article <13649@mimsy.UUCP> I wrote:
>What you can do is simple, if somewhat limited.  The C language assumes
>a `locally flat' address space: any single object has a contiguous address
>space, and a pointer that points somewhere within such an object may be
>used (with pointer arithmetic) to refer to other parts of that object.

Oops: this is probably unclear.  By `single object' I really meant
`single array object', since that is the only case where pointer
arithmetic is legal anyway.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris