www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/02/19/16:01:57

From: gfoot AT mc31 DOT merton DOT ox DOT ac DOT uk (George Foot)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Variable length array ?
Date: 19 Feb 1997 18:50:11 GMT
Organization: Oxford University
Lines: 35
Message-ID: <5efi13$s1o@news.ox.ac.uk>
References: <330B9EDB DOT 79D7 AT post DOT comstar DOT ru>
NNTP-Posting-Host: mc31.merton.ox.ac.uk
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Dim Zegebart (zager AT post DOT comstar DOT ru) wrote:

: void foo(void)
: {
:   int i=0;
:   int arr[i];

:   for(i=0;i<10;i++)
:    {
:      arr[i]=i;
:    }
: }

This won't work; it gives a segmentation fault. You're effectively declaring
'arr' to be an array of 0 integers, then attempting to access arr[0], arr[1],
... arr[9].

The syntax is correct, though, I think. But it's a bit pointless in this
context; the 'int arr[i]' could be replaced with 'int arr[10]', having the
same effect. The whole point of variable length arrays is that the length
of the array cannot be determined at compile-time, and may vary at run-time.
For instance, putting a parameter into your function, then using this as the
size of the array (and the limit of the for loop).

Note that variable length arrays are a gcc extension. For portability you
should use:

int *arr=(int *)malloc(i*sizeof(int));

instead of 'int arr[i];', and remember to free(arr) before the end of the
function.

-- 
George Foot <gfoot AT mc31 DOT merton DOT ox DOT ac DOT uk>
Merton College, Oxford.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019