delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/02/20/10:05:56

Date: Thu, 20 Feb 1997 15:31:53 -0300
Message-Id: <1.5.4.16.19970220114604.2c0f27b0@dmeasc.rc.ipt.br>
Mime-Version: 1.0
To: gfoot AT mc31 DOT merton DOT ox DOT ac DOT uk (George Foot), djgpp AT delorie DOT com
From: Cesar Scarpini Rabak <csrabak AT dce03 DOT ipt DOT br>
Subject: Re: Variable length array ?

At 18:50 19/02/97 GMT, George Foot wrote:
>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.

Also, if you use alloca instead of malloc, athe memory will be released when
the function exits, making unnecessary to free it.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cesar Scarpini Rabak                      E-mail: csrabak AT ipt DOT br
DME/ASC                                   Phone: 55-11-268-3522 Ext.350
IPT - Instituto de Pesquisas Tecnologicas Fax:   55-11-268-5996
Av. Prof. Almeida Prado, 532.  Sao Paulo - SP 05508-901 BRAZIL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

- Raw text -


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