Re: dynamic declaration of struct array
From: Irrwahn Grausewitz (irrwahn33_at_freenet.de)
Date: 10/11/03
- Next message: Irrwahn Grausewitz: "Re: dynamic declaration of struct array"
- Previous message: Mark McIntyre: "Re: How can I open a file, skip first 2 lines and get the 50th character?"
- In reply to: Dave Vandervies: "Re: dynamic declaration of struct array"
- Next in thread: Irrwahn Grausewitz: "Re: dynamic declaration of struct array"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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)
- Next message: Irrwahn Grausewitz: "Re: dynamic declaration of struct array"
- Previous message: Mark McIntyre: "Re: How can I open a file, skip first 2 lines and get the 50th character?"
- In reply to: Dave Vandervies: "Re: dynamic declaration of struct array"
- Next in thread: Irrwahn Grausewitz: "Re: dynamic declaration of struct array"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|