473,800 Members | 2,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic declaration of struct array

Tim
Why won't the declaration of a struct array work if I do it like this:

1 typedef struct
2 {
3 int pens;
4 int pencils;
5 } Stationers;
6

.........

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.
Nov 13 '05 #1
11 16409
Tim wrote:
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.


Stationers *stats = (Stationers*)ma lloc(num * sizeof(Statione rs));

NR

Nov 13 '05 #2
"Tim" <hi**********@y ahoo.co.uk> wrote in message
news:ad******** *************** ***@posting.goo gle.com...
Why won't the declaration of a struct array work if I do it like this: .... 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.


This code is actually valid if your compiler implements the 1999
C standard. Prior to that, array variables are indeed required
to be of a size known at compile time.

The backwards-compatible way to do what you want is to use:
Stationers* stats = (Stationers*)ma lloc(num*sizeof (Stationers));
... use stats as if it were an array of size num ...
free(stats); // don't forget this prior to exit !
Hope this helps,
Ivan
--
http://ivan.vecerina.com


Nov 13 '05 #3
In article <ad************ **************@ posting.google. com>,
Tim <hi**********@y ahoo.co.uk> wrote:
Why won't the declaration of a struct array work if I do it like this:
[snip struct definition]
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(nu m * sizeof *stats);

/*I assume you'll want to do something with stats here*/

free(stats);
}
--------

If you're using C++ (which also allows declarations after non-
declarations), go to comp.lang.c++ and ask about (or, better, open a
textbook and read about) new[] and std::vector.
dave

--
Dave Vandervies dj******@csclub .uwaterloo.ca
So "Patterns" are really just another name for "Object-oriented programming",
which is really just another name for "Structured programming", which is really
just big words for "good hacking". --Richard Bos in comp.lang.c
Nov 13 '05 #4
hi**********@ya hoo.co.uk (Tim) wrote:
Why won't the declaration of a struct array work if I do it like this:

1 typedef struct
2 {
3 int pens;
4 int pencils;
5 } Stationers;
6

.........

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.


Yes, you have to define a pointer and dynamically allocate memory for
it to point to, look:

#include <stdio.h>
#include <stdlib.h>

typedef
struct
{
int pens;
int pencils;
}
Stationers;

int main( void )
{
int num;
Stationers *stats;

/* calculate value for num, e.g: */
num = 42;

stats = malloc( num * sizeof *stats );
if ( stats == NULL )
{
fprintf( stderr, "Memory allocation error." );
return EXIT_FAILURE;
}

/* do something with stats, e.g: */
stats[ 7 ].pens = 6;
stats[ 7 ].pencils = 9;

return EXIT_SUCCESS;
}

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #5
dj******@csclub .uwaterloo.ca (Dave Vandervies) wrote:
Tim <hi**********@y ahoo.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(nu m * sizeof *stats);

/* check malloc() return value here! */
/*I assume you'll want to do something with stats here*/

free(stats); return 0;}

<SNIP>
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #6
Noah Roberts <nr******@donte mailme.com> wrote:
Tim wrote:

[ some code restored ... ]
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.


Stationers *stats = (Stationers*)ma lloc(num * sizeof(Statione rs));


Better:

Stationers *stats = malloc(num * sizeof *stats);

(The cast to is not only unnecessary, it may hide the failure of not
including stdlib.h; sizeof *stats has the advantage that one does not
have to change the malloc expression if the type of stats ever changes.)

But still this won't work in pre-C99 (in this special case): you define
a variable in another place than the beginning of a block. Or, if you
intended to put above line at the top of main(), you don't know the
value for num, as it has to be calculated yet.

So, there's no way around splitting the line up into:

/* goes to top of main(): */
Stationers *stats;

/* after num has been calculated: */
stats = malloc(num * sizeof *stats);

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #7
"Ivan Vecerina" <ivecATmyrealbo xDOTcom> wrote:
"Tim" <hi**********@y ahoo.co.uk> wrote in message
news:ad******* *************** ****@posting.go ogle.com...
Why won't the declaration of a struct array work if I do it like this:...
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.


This code is actually valid if your compiler implements the 1999
C standard. Prior to that, array variables are indeed required
to be of a size known at compile time.

The backwards-compatible way to do what you want is to use:
Stationers* stats = (Stationers*)ma lloc(num*sizeof (Stationers));


Better:

Stationers *stats = malloc(num * sizeof *stats);

(The cast is not only unnecessary, it may hide the failure of not
including stdlib.h; sizeof *stats has the advantage that one does not
have to change the malloc expression if the type of stats ever changes.)

But still this won't work in pre-C99 (in this special case): you define
a variable in another place than the beginning of a block. Or, if you
intended to put above line at the top of main(), you don't know the
value for num, as it has to be calculated yet.

So, there's no way around splitting the line up into:

/* goes to top of main(): */
Stationers *stats;

/* after num has been calculated: */
stats = malloc(num * sizeof *stats);
... use stats as if it were an array of size num ...
free(stats); // don't forget this prior to exit !


Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #8
"Irrwahn Grausewitz" <ir*******@free net.de> wrote in message
news:la******** *************** *********@4ax.c om...
int main( void )
{
int num;
Stationers *stats;

/* calculate value for num, e.g: */
num = 42;

stats = malloc( num * sizeof *stats );
if ( stats == NULL )
{
fprintf( stderr, "Memory allocation error." );
return EXIT_FAILURE;
}

/* do something with stats, e.g: */
stats[ 7 ].pens = 6;
stats[ 7 ].pencils = 9;
add:
free( stats );
return EXIT_SUCCESS;
}


Yes, the memory will be reclaimed at program exit on
any decent OS, but it is a good habit to always free
the memory that you allocate. (e.g. in case the code
gets moved into a loop or another function...).

Cheers,
Ivan
--
http://ivan.vecerina.com
Nov 13 '05 #9
"Ivan Vecerina" <ivecATmyrealbo xDOTcom> wrote:
"Irrwahn Grausewitz" <ir*******@free net.de> wrote in message
news:la******* *************** **********@4ax. com...
int main( void )
{
int num;
Stationers *stats;

/* calculate value for num, e.g: */
num = 42;

stats = malloc( num * sizeof *stats );
if ( stats == NULL )
{
fprintf( stderr, "Memory allocation error." );
return EXIT_FAILURE;
}

/* do something with stats, e.g: */
stats[ 7 ].pens = 6;
stats[ 7 ].pencils = 9;
add:
free( stats );
return EXIT_SUCCESS;
}


Yes, the memory will be reclaimed at program exit on
any decent OS, but it is a good habit to always free
the memory that you allocate. (e.g. in case the code
gets moved into a loop or another function...).


Good point.

Cheers,
Ivan


Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
10129
by: Rave | last post by:
Is there a better way to do this in C++ ? linkedlist * sort_array; for(int i=0; i<MAX; i++) { sort_array = new (linkedlist); sort_array = new (linkedlist); }
19
3086
by: Geetesh | last post by:
Recently i saw a code in which there was a structer defination similar as bellow: struct foo { int dummy1; int dummy2; int last }; In application the above array is always allocated at runtime using malloc.In this last member of the structer "int last" is not
8
3689
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
11
4737
by: Marco Loskamp | last post by:
Dear list, I'm trying to dynamically generate functions; it seems that what I really want is beyond C itself, but I'd like to be confirmed here. In the minimal example below, I'd like to create content to put at the address pointed to by f. In particular, I'd like to avoid/replace the memcpy line. Possible application (inspired by Paul Graham, "ANSI Common Lisp",
2
558
by: Richard | last post by:
Define a record structure to hold a set of test scores, number of tests, and the average score. The number of records are to be determined at runtime. Also the number of tests for each record is to be determined at runtime. Calculate the average test score for the set the set of test scores in each record. Display records. Demonstrate with a least five records. I do not know how to dynamically allocate the number of record and the number...
8
2757
by: Steve Chow | last post by:
I have two structures; struct cordsys { int y, x, length }; struct provinces { int number; int type; struct cordsys cord;
11
2622
by: Martin Eisenberg | last post by:
Hi Antoine, just redirecting you... Antoine Trux wrote: > Hi, > > Is the following code legal: > > ------> code starts here <------ > #include <stddef.h>
9
7315
by: herobeat | last post by:
Hi all, I'm having a hell of a time with declaring a struct to hold some binary data I'm trying to read from some files on disk. What I would like to do is something like this: public struct binHeader { public UInt32 Id; public UInt32 Offset;
10
2245
by: Raman | last post by:
Hi All, Is it valid: struct test{ }; I mean, Can we have a struct containing no members? Is this a an
0
10276
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10035
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9090
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6813
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.