Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!mailrus!uflorida!haven!mimsy!chris
From: chris@mimsy.UUCP (Chris Torek)
Newsgroups: comp.lang.c
Subject: Re: How to do run-time array declaration?
Message-ID: <13649@mimsy.UUCP>
Date: 20 Sep 88 19:33:29 GMT
References: <14502@agate.BERKELEY.EDU>
Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742
Lines: 56

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 

	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