473,626 Members | 3,325 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Referencing a global array outside a function

I need to create a global array whose dimensions depend on the
contents of another global array populated at its initialisation. For
example:

int array1[3]={3,2,1};
int array2[array1[0]]; //should be equiv. to: int array2[3];

GCC gives these errors:
variable-size type declared outside of any function
variable-sized object may not be initialized
warning: excess elements in array initializer
warning: (near initialization for `array2')

Both arrays need to be global and created before main() starts. Any
ideas?
Nov 14 '05 #1
12 2738
On 8 May 2004 07:21:09 -0700, fl******@easy.c om (flipflop) wrote:
I need to create a global array whose dimensions depend on the
contents of another global array populated at its initialisation. For
example:

int array1[3]={3,2,1};
int array2[array1[0]]; //should be equiv. to: int array2[3];

GCC gives these errors:
variable-size type declared outside of any function
variable-sized object may not be initialized
warning: excess elements in array initializer
warning: (near initialization for `array2')

Both arrays need to be global and created before main() starts. Any
ideas?


#include <stdio.h>

#define arrsize(a) (sizeof(a) / sizeof(*a))

int array1[3]={3,2,1};
int array2[arrsize(array1)]; /*should be equiv. to: int array2[3]; */

int main()
{
printf("sizeof( array1) = %d\n", sizeof(array1)) ;
printf("sizeof( array2) = %d\n", sizeof(array2)) ;
return 0;
}

Output:
sizeof(array1) = 12
sizeof(array2) = 12

-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #2
On 2004-05-08, flipflop <fl******@easy. com> wrote:
I need to create a global array whose dimensions depend on the
contents of another global array populated at its initialisation. For
example:

int array1[3]={3,2,1};
int array2[array1[0]]; //should be equiv. to: int array2[3];


#define ARRAY1_MAX (3)
#define ARRAY1(n) (ARRAY1_MAX - (n))

int array1[3] = { ARRAY1(0), ARRAY1(1), ARRAY1(2) };
int array2[ARRAY1(0)];

-- James
Nov 14 '05 #3
flipflop wrote:
I need to create a global array whose dimensions depend on the
contents of another global array populated at its initialisation. For
example:

int array1[3]={3,2,1};
int array2[array1[0]]; //should be equiv. to: int array2[3];


enum { constant_expres sion = 3 };
int array1[3] = { constant_expres sion, 2, 1};
int array2[constant_expres sion];

Jeremy.
Nov 14 '05 #4
In 'comp.lang.c', Leor Zolman <le**@bdsoft.co m> wrote:
#define arrsize(a) (sizeof(a) / sizeof(*a))


It's

#define arrsize(a) (sizeof(a) / sizeof *(a))

(Parens rulez)

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #5
On 08 May 2004 15:13:41 GMT, Emmanuel Delahaye <em**********@n oos.fr>
wrote:
In 'comp.lang.c', Leor Zolman <le**@bdsoft.co m> wrote:
#define arrsize(a) (sizeof(a) / sizeof(*a))
It's

#define arrsize(a) (sizeof(a) / sizeof *(a))

(Parens rulez)


Thanks... I must never have been bitten by that one (yet) ;-)
-leor


--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #6
Leor Zolman <le**@bdsoft.co m> writes:
On 8 May 2004 07:21:09 -0700, fl******@easy.c om (flipflop) wrote:
I need to create a global array whose dimensions depend on the ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^contents of another global array populated at its initialisation. For ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^example:

int array1[3]={3,2,1};
int array2[array1[0]]; //should be equiv. to: int array2[3];

GCC gives these errors:
variable-size type declared outside of any function
variable-sized object may not be initialized
warning: excess elements in array initializer
warning: (near initialization for `array2')

Both arrays need to be global and created before main() starts. Any
ideas?


#include <stdio.h>

#define arrsize(a) (sizeof(a) / sizeof(*a))

int array1[3]={3,2,1};
int array2[arrsize(array1)]; /*should be equiv. to: int array2[3]; */

int main()
{
printf("sizeof( array1) = %d\n", sizeof(array1)) ;
printf("sizeof( array2) = %d\n", sizeof(array2)) ;
return 0;
}


I don't think that's what the OP wanted (see underlined text). `array2'
shouldn't have 3 elements because `array1' has three elements, but because
the zeroth element of `array1' is 3.

The answer is: it cannot be done directly. One possibility is to define
a macro which expands to `3', and use it to both initialize the zeroth
element of `array1' and define the size of `array2'.

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #7
On Sat, 08 May 2004 21:21:26 +0200, Martin Dickopp
<ex************ ****@zero-based.org> wrote:
Leor Zolman <le**@bdsoft.co m> writes:
On 8 May 2004 07:21:09 -0700, fl******@easy.c om (flipflop) wrote:
I need to create a global array whose dimensions depend on the ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^contents of another global array populated at its initialisation. For
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^


I don't think that's what the OP wanted (see underlined text). `array2'
shouldn't have 3 elements because `array1' has three elements, but because
the zeroth element of `array1' is 3.
Yup; a case of overloaded 3's ;-)
Thanks,
-leor

The answer is: it cannot be done directly. One possibility is to define
a macro which expands to `3', and use it to both initialize the zeroth
element of `array1' and define the size of `array2'.

Martin


--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #8
Martin Dickopp <ex************ ****@zero-based.org> wrote in message news:<cu******* ******@zero-based.org>...
I don't think that's what the OP wanted (see underlined text). `array2'
shouldn't have 3 elements because `array1' has three elements, but because
the zeroth element of `array1' is 3.

The answer is: it cannot be done directly. One possibility is to define
a macro which expands to `3', and use it to both initialize the zeroth
element of `array1' and define the size of `array2'.


Guys - thanks for your replies. I probably should have asked the
question more simply, as:

" How can you reference a global array element, set during the
array's initialisation, before main() starts? For example:
int array[3]={3,2,1};
int x=array[0];
main() { ... "

It seems it's not possible but I can fudge around it. Thanks again.
(Nice photos by the way Martin.)
Nov 14 '05 #9
On 10 May 2004 05:30:38 -0700, fl******@easy.c om (flipflop) wrote:
Martin Dickopp <ex************ ****@zero-based.org> wrote in message news:<cu******* ******@zero-based.org>...
I don't think that's what the OP wanted (see underlined text). `array2'
shouldn't have 3 elements because `array1' has three elements, but because
the zeroth element of `array1' is 3.

The answer is: it cannot be done directly. One possibility is to define
a macro which expands to `3', and use it to both initialize the zeroth
element of `array1' and define the size of `array2'.
Guys - thanks for your replies. I probably should have asked the
question more simply, as:

" How can you reference a global array element, set during the
array's initialisation, before main() starts? For example:
int array[3]={3,2,1};
int x=array[0];
main() { ... "


Actually, the issues don't change much depending on /what/ you want to use
that value for...the bottom line, as you've acknowledged below, is that C
does not allow dereferencing operations in constant expressions (and array
subscripting is typically translated into code involving pointer
dereferencing.)

I'm not sure why you're so determined to be able to do this, since (as has
been pointed out), it is actually simpler and more direct to just take the
same expression that you've placed into the array initializer list and
reuse it the next time you need it. What is so gosh-darn important about
having to "extract it out of the array", anyway? I've always gotten the
feeling there was more to this problem than you've shown, but that if you
were to fully explain the problem you're trying to solve, ultimately we'd
all conclude that the most straightforward solution wouldn't require this
capability you've been asking about.
-leor



It seems it's not possible but I can fudge around it. Thanks again.
(Nice photos by the way Martin.)

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #10

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

Similar topics

7
1366
by: VK | last post by:
.... or my script, or my mind, or both? <html> <head> <title>Test</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script> function init() { var arr = document.getElementsByTagName('DIV');
17
12277
by: Davor | last post by:
How to define global variable in main()? I'm asking because I have an array in main, whose size is determined by input, so the definition has to be in main ( or in some other funcion ). And I need to use that array in my other functions, so I want it to be global. I tryed using extern keyword, but I gut some error, so I supose that's not it. thanks in advance Davor :-)
4
9612
by: Aniruddha | last post by:
I want to initialize an array of function pointers (global) If I do it like: /* definition of foo_1, foo_2, foo_3 all return void and take no args */ void (* foo) (); foo = foo_1 ; foo = foo_2 ; foo = foo_3 ; I get a compile time error, but if initialized like :
7
3127
by: Michael | last post by:
Hi newsgroup, as the subject indicates I am looking for an advice using global variables. I am not if this problem is more about style then C. If its wrong in thi group, sorry. So I have a couple of function that all need the same information (all located in the same file). By now it looks like /* file beginns */
8
3507
by: chellappa | last post by:
hi Everybody ! decalaring variable in a.h and using that vaaariable in a1.c and inalization is in main.c it is possible .........pleaase correct that error is it Possible? i am trying it gives error! In file included from main.c:2: a1.c:3: error: initializer element is not constant
4
21699
by: Bilgehan.Balban | last post by:
Hi, The following code: #include <stdio.h> // const int const_asize = 10; #define define_asize = 10; int array = {1,2,3,4,5,6,7,8,9,0};
10
2644
by: Charles O'Flynn | last post by:
As a complete newcomer (2-3 days) to PHP, although not to programming in general, I have 'dived in' to start a small project to read and parse an XML data stream. I have already worked out most of the more specialist aspects of the job but am now completely stuck on something I would have thought were simplicity itself... I need to have a large number of global variables visible inside functions - it's not possible to pass them into the...
4
67222
moishy
by: moishy | last post by:
I have a function which adds strings to an array, but outside the function it didn't add the string to the array. Example: function AddStringToArray($name,$string) { $theArray = $string; print "inside the function: ".$theArray."<p>"; }
1
29338
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this condition. The opinions expressed in this article are those of the author alone although many have...
0
8705
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...
0
8638
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
8365
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
8505
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
6125
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
5574
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
4092
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...
0
4198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1511
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.