How to do run-time array declaration?

Chris Torek chris at mimsy.UUCP
Wed Sep 21 05:33:29 AEST 1988


In article <14502 at agate.BERKELEY.EDU> c60c-4br at 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 at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list