473,491 Members | 1,917 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Declare an array with a size based on a variable...

I would like to have an array declaration where the size of the array
is dependent on a variable. Something like this:

/* Store the desired size of the array in a variable named
"array_size". */
unsigned short int array_size = 25;

/*Declare an array named "numbers" using the variable initialized
above. */
unsigned short int numbers[array_size];

I think that this syntax will work. However, my real problem is this. I
need to include this array in a struct definition that will be in a
header file. Am I allowed to have the "array_size" variable
initialization statement in my header file, and if not, how do I
indicate that the size of the array in my struct is based on a
variable, and not a literal number?

Thanks for the help.

Scott Huey

Aug 1 '06 #1
8 10140
re****************@gmail.com wrote:
I would like to have an array declaration where the size of the array
is dependent on a variable. Something like this:

/* Store the desired size of the array in a variable named
"array_size". */
unsigned short int array_size = 25;

/*Declare an array named "numbers" using the variable initialized
above. */
unsigned short int numbers[array_size];

I think that this syntax will work. However, my real problem is this. I
need to include this array in a struct definition that will be in a
header file. Am I allowed to have the "array_size" variable
initialization statement in my header file, and if not, how do I
indicate that the size of the array in my struct is based on a
variable, and not a literal number?

Thanks for the help.

Scott Huey
You can declare a structure like this in standard C:

struct M {
int size;
int data[];
};

This is a structure that ends with a flexible array, i.e. an
array of an underminate size.

What you want to do is, however:

struct M {
int size;
int data[size];
};

but this is not allowed. It would be a nice extension of
the language, since variable length structures make no sense
in most cases without some size data. But the standard has
not provided any way to do this.

jacob
Aug 1 '06 #2
re****************@gmail.com wrote:
I would like to have an array declaration where the size of the array
is dependent on a variable. Something like this:

/* Store the desired size of the array in a variable named
"array_size". */
unsigned short int array_size = 25;

/*Declare an array named "numbers" using the variable initialized
above. */
unsigned short int numbers[array_size];
If this is really a fixed value, just use a constant value via #define.

Otherwise, my understanding is that you cannot declare and define an
array in terms of another declared int value (with the caveats discussed
else-thread).
Aug 1 '06 #3
C99 allows code like that:
int a=10;
int b[a];

Be careful though. Older compilers
won't compile the above.

--
Papastefanos Serafeim

"Clever Monkey" <cl**************@hotmail.com.invalidwrote in message
news:9S*****************@nnrp.ca.mci.com!nnrp1.uun et.ca...
re****************@gmail.com wrote:
>I would like to have an array declaration where the size of the array
is dependent on a variable. Something like this:

/* Store the desired size of the array in a variable named
"array_size". */
unsigned short int array_size = 25;

/*Declare an array named "numbers" using the variable initialized
above. */
unsigned short int numbers[array_size];
If this is really a fixed value, just use a constant value via #define.

Otherwise, my understanding is that you cannot declare and define an array
in terms of another declared int value (with the caveats discussed
else-thread).

Aug 1 '06 #4
jacob navia schrieb:
re****************@gmail.com wrote:
>I would like to have an array declaration where the size of the array
is dependent on a variable. Something like this:

/* Store the desired size of the array in a variable named
"array_size". */
unsigned short int array_size = 25;

/*Declare an array named "numbers" using the variable initialized
above. */
unsigned short int numbers[array_size];

I think that this syntax will work. However, my real problem is this. I
need to include this array in a struct definition that will be in a
header file. Am I allowed to have the "array_size" variable
initialization statement in my header file, and if not, how do I
indicate that the size of the array in my struct is based on a
variable, and not a literal number?

You can declare a structure like this in standard C:

struct M {
int size;
int data[];
};

This is a structure that ends with a flexible array, i.e. an
array of an underminate size.
As the above is a C99 feature and the OP may not have a C99
compiler, I suggest reading about the "struct hack":
http://c-faq.com/struct/structhack.html

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Aug 1 '06 #5
jacob navia <ja***@jacob.remcomp.frwrites:
re****************@gmail.com wrote:
>I would like to have an array declaration where the size of the array
is dependent on a variable. Something like this:
/* Store the desired size of the array in a variable named
"array_size". */
unsigned short int array_size = 25;
/*Declare an array named "numbers" using the variable initialized
above. */
unsigned short int numbers[array_size];
I think that this syntax will work. However, my real problem is
this. I
need to include this array in a struct definition that will be in a
header file. Am I allowed to have the "array_size" variable
initialization statement in my header file, and if not, how do I
indicate that the size of the array in my struct is based on a
variable, and not a literal number?
Thanks for the help.
Scott Huey

You can declare a structure like this in standard C:

struct M {
int size;
int data[];
};

This is a structure that ends with a flexible array, i.e. an
array of an underminate size.
What jacob isn't bothering to tell you is that this feature is
specific to C99 (the 1999 ISO C standard). It is likely not to be
supported by many current compilers; using it will limit the
portability of your code.

Flexible array members are intended to legitimize a common trick known
as the "struct hack". It's been said that use of the struct hack
*might* invoke undefined behavior, but I'd be surprised to see an
implementation that doesn't support it.

The idea is that you declare a structure like this:

struct M {
int size;
int data[1];
};

and then use malloc() to allocate enough space for a struct M plus
however many additional int elements you need. Here's a brief example:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct M {
int size;
int data[1];
};
int count = 25;
int i;
struct M *ptr = malloc(sizeof *ptr + (count-1) * sizeof(int));

ptr->size = count;
for (i = 0; i < count; i ++) {
ptr->data[i] = i;
}

printf("ptr->size = %d\n", ptr->size);
for (i = 0; i < count; i ++) {
printf("ptr->data[%d] = %d\n", i, ptr->data[i]);
}
return 0;
}

A cleaner alternative is to use a pointer to (the first element of) an
array rather than putting the (flexible) array inside the structure
itself:

struct M {
int size;
int *data_ptr;
};

This means you have to allocate two separate objects, making memory
management more difficult.
What you want to do is, however:

struct M {
int size;
int data[size];
};

but this is not allowed. It would be a nice extension of
the language, since variable length structures make no sense
in most cases without some size data. But the standard has
not provided any way to do this.
Probably because it would be difficult (not impossible) to nail down
all the corner cases. I can think of several questions that would
have to be answered; the answers are far from obvious.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 1 '06 #6
Michael Mair <Mi**********@invalid.invalidwrites:
[...]
As the above is a C99 feature and the OP may not have a C99
compiler, I suggest reading about the "struct hack":
http://c-faq.com/struct/structhack.html
Thanks, I would saved some time if I'd found that myself. (I missed
it because the FAQ doesn't use the phrase "struct hack"; it probably
should.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 1 '06 #7
Keith Thompson wrote:
>
>>What you want to do is, however:

struct M {
int size;
int data[size];
};

but this is not allowed. It would be a nice extension of
the language, since variable length structures make no sense
in most cases without some size data. But the standard has
not provided any way to do this.


Probably because it would be difficult (not impossible) to nail down
all the corner cases. I can think of several questions that would
have to be answered; the answers are far from obvious.
I mean if we see the structure declaration as a scope (what it is
for the names of the structure members) any unqualified name in the
array index would be looked up in the previously declared members.
If it is found and it is of a type suitable for an array index, then
that would mean that the sizeof() operation in structure M woould be

sizeof(M) + sizeof(size)+typeof(data)*size + alignment;

sizeof(M) is the sizeof operation as applied to this structure i.e.
without the flexible member as specified by C99.

sizeof(size) would be the size of the index type (in this case
sizeof(int).

typeof(data)*size would multiply the type of the flexible array times
the integer expression in the index. This way you could specify:

struct M {
int size;
int data[size+1]; // Integer expression.
};

This is fairly straightforward. What "corner cases" you have
in mind?
Aug 1 '06 #8
jacob navia <ja***@jacob.remcomp.frwrites:
Keith Thompson wrote:
>>>What you want to do is, however:

struct M {
int size;
int data[size];
};

but this is not allowed. It would be a nice extension of
the language, since variable length structures make no sense
in most cases without some size data. But the standard has
not provided any way to do this.
Probably because it would be difficult (not impossible) to nail down
all the corner cases. I can think of several questions that would
have to be answered; the answers are far from obvious.

I mean if we see the structure declaration as a scope (what it is
for the names of the structure members) any unqualified name in the
array index would be looked up in the previously declared members.
If it is found and it is of a type suitable for an array index, then
that would mean that the sizeof() operation in structure M woould be

sizeof(M) + sizeof(size)+typeof(data)*size + alignment;
What is "size" in this expression? Is "typeof(data) supposed to be
"sizeof(data)"?
sizeof(M) is the sizeof operation as applied to this structure i.e.
without the flexible member as specified by C99.

sizeof(size) would be the size of the index type (in this case
sizeof(int).

typeof(data)*size would multiply the type of the flexible array times
the integer expression in the index. This way you could specify:

struct M {
int size;
int data[size+1]; // Integer expression.
};

This is fairly straightforward. What "corner cases" you have
in mind?
Ok, suppose you have:

struct M {
int size;
double data[size];
};
struct M obj = { 100 };

(There's no initializer for the "data" member, so it's set to zeros or
whatever.)

Are you saying that sizeof obj would be
(sizeof(int) + obj.size*sizeof(double))
? What about sizeof(struct M)? What if I then do:

obj.size = 200;

Does this implicitly reallocate the structure? Is the user expected
to reallocate the structure? Does it cause sizeof(obj) to be
inconsistent?

Or does the user have to allocate the object manually, making sure to
get the size right? If so, it's just the struct hack with a light
sprinkling of syntactic sugar.

If you have this:

struct M2 {
int size;
double data1[size];
double data2[size];
};

then data2 will have a non-constant size *and* be at a non-constant
offset.

If this were to be standardized, I'd probably suggest requiring any
member whose value affects the size of any other member to be declared
const; any such members must be initialized to some value when the
object is declared. Presumably you wouldn't be able to have an array
of these things, unless perhaps each element of the array has the same
value for "size". And if you allocate a struct M using malloc(), you
can't set the size without cheating (casting away const).

I'm sure there are plenty of things I haven't thought of.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 1 '06 #9

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

Similar topics

4
1540
by: Tom Page | last post by:
Hello all I have a question that may or may not be simple - I need my three dimensional array to be of the form: array where jj and kk range from 0 to some constant fixed at the very...
7
3154
by: Irish | last post by:
Hello all :) Hopefully someone can shed some light on this problem I'm having. I'm trying to declare a variable to a type of class I've defined (which is a minHeap), but actually instantiate it...
9
10675
by: dati_remo | last post by:
Hi, is it possible to find the dimension of an array using a pointer? main() { int a; f(a); return; }
11
4429
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to...
4
7268
by: emma middlebrook | last post by:
Hi Straight to the point - I don't understand why System.Array derives from IList (given the methods/properties actually on IList). When designing an interface you specify a contract. Deriving...
15
5299
by: Geoff Cox | last post by:
Hello, Can I separately declare and initialize a string array? How and where would I do it in the code below? It was created using Visual C++ 2005 Express Beta 2 ... In C# I would have ...
4
2817
by: ankurdave | last post by:
Is it possible to declare a class member variable in the constructor? For example, class SomeClass { public: SomeClass() { int SomeArray; } }
4
4550
by: mab464 | last post by:
I have this code on my WAMP server running on my XP machine if ( isset( $_POST ) ) { for($i=0; $i<count($_POST);$i++) { if ($ans != NULL ) $ans .= ", " . $_POST ; // Not the first...
33
7123
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d...
0
7118
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6980
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7192
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...
0
5452
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,...
0
4579
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...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1397
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 ...
1
637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.