Re: dynamic declaration of struct array

From: Irrwahn Grausewitz (irrwahn33_at_freenet.de)
Date: 10/11/03


Date: Sat, 11 Oct 2003 00:23:35 +0200

dj3vande@csclub.uwaterloo.ca (Dave Vandervies) wrote:

>Tim <hillbilly010@yahoo.co.uk> wrote:
<SNIP>
>>7 int main(void)
>>8 {
>>9 int num;
>>
>> ...........num defined in code........
>>
>>10
>>11 Stationers stats[num];
>>12 }
>>
>>The error message says "constant expression required" and highlights
>>line 11. I want to declare it dynamically during runtime, could
>>someone explain how to do this please.
>
>Uhmm... what language are you trying to write this code in?
>
>If you're using C99, what you have here should work, since arrays are
>allowed to have lengths that aren't known until run-time.
>
>If you're using C90, you're not allowed to declare a new variable (like
>the array) after non-declaration stuff (like assigning a value to num),
>so once you fill in the blanks your code will still be broken no matter
>how you declare the array. Instead, you'd need to declare a pointer at
>the beginning of the block and, once you've decided how many elements
>you want, use malloc to allocate memory for it:
>--------
>#include <stdlib.h>
>
>/*Define and typedef the Stationers struct here*/
>
>int main(void)
>{
> int num;
> Stationers *stats;
>
> /*Decide on a value for num here*/
>
> stats=malloc(num * sizeof *stats);
        /* check malloc() return value here! */
>
> /*I assume you'll want to do something with stats here*/
>
> free(stats);
        return 0;
>}
<SNIP>

-- 
Irrwahn 
(irrwahn33@freenet.de)


Relevant Pages

  • Re: vb.net class
    ... about fixed array lenghts or using ReDim statements. ... code ensures everything in the array is a String because you declare it ... Count can be generated from the time list, not need to store ...
    (microsoft.public.dotnet.languages.vb)
  • Re: NotSupportedException TomTomSDK
    ... The easiest way to marshal this data is as a byte array. ... use the System.Text.Encoding.Unicode.GetString to extract the inline string. ... BitConverter will allow you to get the int members out of the byte ... > Any ideas how to declare the TCHAR? ...
    (microsoft.public.pocketpc.developer)
  • Re: Warning on assigning a function-returning-a-pointer-to-arrays
    ... reminder that it's a pointer and not merely a locally declared array ... That would indicate a bug in the compiler, ... int main{ ...
    (comp.lang.c)
  • Re: static array initialization in a class
    ... you declare a pointer and use it as an "array". ... For starters, you don't initialise arr. ... Even if those blocks were totally empty before you declared the int*, ...
    (comp.lang.cpp)
  • Cursor operations
    ... DECLARE @array TABLE (nameID INT NOT NULL, ... DECLARE arrayCursor CURSOR SCROLL FOR SELECT nameID, ... DECLARE @index INT, @count INT, @offset INT ...
    (microsoft.public.sqlserver.programming)