473,796 Members | 2,578 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to define global variable in main()



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 :-)

Nov 13 '05 #1
17 12290
Davor wrote:


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 :-)


Is there a reason why you don't just past that array to every function
that needs to access it?

Nov 13 '05 #2
Jeff wrote:
Davor wrote:


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 :-)


Is there a reason why you don't just past that array to every function
that needs to access it?


s/past/pass/g

Ugh!

Nov 13 '05 #3
In article <3F************ @yahoo.com>, Davor wrote:
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.


#include <stdlib.h>

int *global_array;

int get_user_input( void);
void go(void);

int main(void)
{
int x = get_user_input( );
global_array = malloc(x * *global_array);
if (global_array != 0) {
go();
}
return 0;
}
/* etc... */

--
Neil Cerutti
Nov 13 '05 #4
Neil Cerutti wrote:

<snip>
global_array = malloc(x * *global_array);


ITYM

global_array = malloc(x * sizeof *global_array);

<snip>

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #5
Davor <da*********@ya hoo.com> wrote (02 Jul 2003) in
news:3F******** ****@yahoo.com / comp.lang.c:


How to define global variable in main()?
main() is a function. Any variable declared in main will have block
scope. Variables with file scope and external linkage should be
declared *outside* of any function.
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 ).
Not true. A pointer can be declared outside a function, as can a
variable holding size information. The allocation occurs in a function,
but so what?
And I need to use that array in my other functions, so I want it to be
global.


If you have a good reason to avoid passing the array name as an
argument, then declare it as file scope. Try to avoid the word
"global", since it could have several meanings. Use the words for which
there is a clear meaning in C (scope, linkage, duration).

--
Martin Ambuhl
Returning soon to the
Fourth Largest City in America
Nov 13 '05 #6
In article <bd**********@h ercules.btinter net.com>, Richard Heathfield wrote:
Neil Cerutti wrote:

<snip>
global_array = malloc(x * *global_array);


ITYM

global_array = malloc(x * sizeof *global_array);


Oops!

--
Neil Cerutti
Nov 13 '05 #7
The size of an array must be determined at compliled session!
it can't be determined at running session!

"Davor" <da*********@ya hoo.com> ??????:3F****** ******@yahoo.co m...


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 :-)

Nov 13 '05 #8
hercules wrote:
The size of an array must be determined at compliled session!
it can't be determined at running session!


Hercules...

Not true. See http://www.iedu.com/mrd/c/tokenize.c for an
example; then see http://www.iedu.com/mrd/c/tokfile.c for an
example (that uses the code from the first example) that
dynamically produces an array of pointers to dynamically produced
arrays.

Neither of these pieces of code know the size of the arrays being
produced until discovering that the final element has been
processed - at which time the memory for the entire array is
allocated and the element values stored.

Both sources contain a short test program with which you're
welcome to play to convince yourself that it really does work as
I describe. :)
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #9
Martien Verbruggen wrote:
On Wed, 02 Jul 2003 21:09:25 -0500,
Morris Dovey <mr*****@iedu.c om> wrote:
hercules wrote:
The size of an array must be determined at compliled session!
it can't be determined at running session!


Hercules...

Not true. See http://www.iedu.com/mrd/c/tokenize.c for an

\begin{pedantry }

There are no arrays in that program. There are pointers and
allocations with malloc, but that doesn't make an array.

\end{pedantry}

I suspect that hercules was talking about real arrays, and in c89 the
size of those does need to be known at compile time.


(more pedantic 8-)

C99: 7.20.3.1

"The order and contiguity of storage allocated by successive
calls to the calloc, malloc, and realloc functions is
unspecified. The pointer returned if the allocation succeeds is
suitably aligned so that it may be assigned to a pointer to any
type of object and then used to access such an object or an array
of such objects in the space allocated (until the space is
explicitly deallocated)." [remainder of paragraph dropped]

(less pedantic)

Looks like an array to me.
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #10

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

Similar topics

12
5885
by: David WOO | last post by:
Hi, I am a newbie on C++, I need to define some global variables which should be accessible to most classes. In the mean time, I don't won't the global variables be modified freely at most of these classes. I know there is a pattern called singleton can more or less do such a trick. I am wondering is this the best way to do it (regarding the convenience and safety), as this is such a fundamental thing, I believe most of you have a say...
97
27823
by: s | last post by:
Can I do this: #define MYSTRING "ABC" .. .. .. char mychar = MYSTRING; .. .. ..
34
3695
by: Dennis | last post by:
I would like to dynamically allocate in a sub a 2 dimensional Array float *myarray = new float ; of course I get an error. How do you allocate a 2D array using the New operator? I currently use static float gxy;
6
677
by: David T. Ashley | last post by:
Hi, In my project, I typically declare and define variables in the .H file, i.e. DECMOD_MAIN UINT8 can_message_201_status_global #ifdef MODULE_MAIN = HAS_NEVER_BEEN_RECEIVED #endif ;
7
7010
by: Peng Yu | last post by:
I'm not very clear about when to use #define and when to use const? #define number 4 const int number = 4; If I just want to define a global constant, which way of the above is better? Thanks, Peng
8
3514
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
1433
by: Sheldon | last post by:
Hi, I have a series of classes that are all within the same file. Each is called at different times by the main script. Now I have discovered that I need several variables returned to the main script. Simple, right? I thought so and simply returned the variables in a tuple: (a,b,c,d,e) = obj.method() Now I keep getting this error: "ValueError: unpack tuple of wrong size"
9
3737
by: blangela | last post by:
Can somepoint me to a good discussion on the pros and cons of using #define versus a constant variable in your C+ application? Thanks, Bob
1
6284
by: lumumba401 | last post by:
Hello everybody, i am asking about how to define a bidimensional dynamic array as a global variable to use as incoming variable in a function Let us see , for example in a part of a programm my problem: #include<iostream> ... using namespace std;
0
9684
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
9530
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10459
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
10017
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
9055
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...
1
7552
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
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.