473,774 Members | 2,176 Online
Bytes | Software Development & Data Engineering Community
+ 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 10167
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!nnrp 1.uunet.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
initializati on 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.re mcomp.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
initializati on 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_Keit h) 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**********@i nvalid.invalidw rites:
[...]
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_Keit h) 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)+ty peof(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)*si ze 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.re mcomp.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)+ty peof(data)*size + alignment;
What is "size" in this expression? Is "typeof(dat a) supposed to be
"sizeof(dat a)"?
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)*si ze 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_Keit h) 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
1551
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 beginnning of the program (currently 20) but goes from 0 to some boundary that depends on calculations performed within the program. I know it is possible
7
3168
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 later when I get a command from the user. This is my class and if you look down a lil you can see what I'm trying to do in my main(). I want to ask for the size from the user, but when I try to I can't get my code to compile. Here is the class...
9
10690
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
4469
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 accomplish. // - - - - - - - - begin code - - - - - - - typedef int sm_t; typedef int bg_t; sm_t sm; bg_t bg;
4
7296
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 from an interface and only implementing some of it means something is wrong: either the interface specification is wrong e.g. not minimal or the derivation is wrong e.g. the type can't actually honour this contract.
15
5325
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 private string myArray;
4
2835
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
4561
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 element so append a comma
33
7186
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 array, so im inputting the dimensions of those myself. The problem is that the output array (C=A*B) has as many rows as A and as many columns as B. I would think of initialising C with:
0
9621
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10267
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10040
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
9914
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...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
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
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4012
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
3
2852
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.