473,395 Members | 1,885 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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 12247
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.powernet.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*********@yahoo.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**********@hercules.btinternet.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*********@yahoo.com> ??????:3F************@yahoo.com...


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.com> 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
E. Robert Tisdale wrote:
Don't do that. Instead, do something like this: #endif//GUARD_RAMP_H


But not exactly like that. C99:6.10 specifies a syntax requiring
that #endif be followed by the new-line character.

While it's true that at least some implementations don't issue
diagnostics for intervening comments; it's probably not in the
OP's best interest to be given examples with syntax errors.
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #11
Morris Dovey <mr*****@iedu.com> wrote:
E. Robert Tisdale wrote:
Don't do that. Instead, do something like this:
#endif//GUARD_RAMP_H


But not exactly like that. C99:6.10 specifies a syntax requiring
that #endif be followed by the new-line character.


6.10 applies in translation phase 4 - comments are replaced by single
spaces in translation phase 3, and 6.10 allows space and horizontal-tab
characters between preprocessing tokens (in this case, between endif and
new-line).
While it's true that at least some implementations don't issue
diagnostics for intervening comments; it's probably not in the
OP's best interest to be given examples with syntax errors.


I suspect you are thinking of the older practice of

#endif TEXT_HERE_NOT_COMMENTED

- Kevin.

Nov 13 '05 #12
In <Xn********************************@207.217.77.2 3> Martin Ambuhl <ma*****@earthlink.net> writes:
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).


Most of the time, we can figure out what a newbie means by "global",
but most newbies don't have the slightest clue about the clear meaning
of "scope, linkage, duration" in C.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #13
On 3 Jul 2003 11:04:10 GMT,
Dan Pop <Da*****@cern.ch> wrote:
In <3F**************@iedu.com> Morris Dovey <mr*****@iedu.com> writes:
Martien Verbruggen wrote:
[in response to link to code posted, with reference to arrays]
\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}
(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.
Nope, Martien is right. Look up the definition of "array type":


[snip]
OTOH, the standard is loosely using the term "array", so both parties can
invoke their arguments.


I came to the same conclusion when I started rereading the standard
(C99). While array type is precisely defined, the term array is used
much more fuzzily. That's when I decided I'd wait until someone else
voiced an opinion on the matter.

I was obviously thinking of the strictly defined "array type", while
Morris was thinking of the more fuzzy "array".

Martien
--
|
Martien Verbruggen | Make it idiot proof and someone will make a
Trading Post Australia | better idiot.
|
Nov 13 '05 #14
Dan Pop wrote:
In <3F**************@iedu.com> Morris Dovey <mr*****@iedu.com> writes:

Martien Verbruggen wrote:
On Wed, 02 Jul 2003 21:09:25 -0500,
Morris Dovey <mr*****@iedu.com> 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.


Nope, Martien is right. Look up the definition of "array type":

* An array type describes a contiguously allocated set of objects
with a particular member object type, called the element type. Array
types are characterized by their element type and by the number of
members of the array. ^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^
Ignoring C99 VLAs, if you don't know the number of members of the array,
you can't have a (complete) array type.

OTOH, the standard is loosely using the term "array", so both parties can
invoke their arguments.


Hmm. I hardly ever malloc space for an array without knowing the
number of members.

I guess I just don't do pedantic very well (although I'm pleased
to report that the code is highly portable and seems to function
as intended); and that I find it helpful to think of the mallc'd
region as an array. It doesn't bother me that the number of
members wasn't known at compile time and that the size needed to
be "discovered" during execution.
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #15
Mark McIntyre wrote:
<mode pedantic = extreme>
It may smell like an array, and it may even look like one, but it
aint.

6.2.5(20)
.... Array types are characterized by their element type and by the
number of elements in the array....

The object returned by *alloc has neither of these characteristics.

</mode>


In static char *chars(void), n is an unsigned int used to count
characters, and x is a pointer to char. When the function has
found all of the characters in a word, it does:

x = malloc((n+1) * sizeof(char));

Assuming the allocation succeeds (and assuming the programmer
isn't spoofing anywhere), x now points to an array of n+1 members
of type char. Using "sizeof(char)" in the expression wasn't
necessary, but was intended to emphasize the element type.

The following statement

x[n] = '\0';

emphasizes the array nature of x. I could have written

*(x+n) = '\0';

to de-emphasize x's array nature.

In the function static char **words(void), n is an unsigned int
used to count the words (NUL-terminated arrays of type char)
produced by chars(); and x is a pointer to pointer(s) to chars.
When the function has found all of the words in a line, it does

x = malloc((n+1) * sizeof(char *));

Again, assuming the allocation succeeds, x points to an array of
pointers to words. The following statement,

x[n] = NULL;

emphasizes the array nature of x. I would have coded

*(x+n) = NULL;

if I'd wanted to downplay the array aspect.

In both functions, the number and type of members /is/ known. The
type is known (and specified) at compile time; and the number is
determined at execution time.

If we decide that in order for there to be an array, we must
inform the compiler of the number of elements, then there is a
great deal of corrective work to be done on the standard; and we
should probably drop all references to VLAs. I'm of the opinion
that while the number of elements does need to be known, it
doesn't need to be known at compile time.

BTW, Mark, have you completed your relocation? (Sorry I couldn't
contribute a bottle of wine for your housewarming!)
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #16
Mark McIntyre wrote:
On Thu, 03 Jul 2003 21:26:08 -0500, in comp.lang.c , Morris Dovey
<mr*****@iedu.com> wrote:
Mark McIntyre wrote:
6.2.5(20)
.... Array types are characterized by their element type
and by the number of elements in the array....

The object returned by *alloc has neither of these characteristics.
x = malloc((n+1) * sizeof(char));

Assuming the allocation succeeds (and assuming the
programmer isn't spoofing anywhere), x now points to an
array of n+1 members of type char.


My problem is that x knows neither the type of the element,
nor the number of them.


Not sure how you can say that, given that x was declared and
defined as a pointer to char (so that both programmer and
compiler know the type of the element); and the exact number of
elements (known to the program, if not the compiler) is specified
in the malloc call.
The following statement

x[n] = '\0';

emphasizes the array nature of x.


Well I reckon it emphasises that the C standard requires
malloc to give the appearance that it contiguously allocated
memory, so that you can by good fortune use array style
notation on such memory blocks !!


It's hardly a matter of good fortune. It's the straightforeward
application of the C language's array access mechanism; where
a[i] is defined as equivalent to *(a + i). The pointer returned
by malloc is /required/ to be suitable for use as a pointer to
the array of char.
In both functions, the number and type of members /is/ known.

By you, yes, Not by the compiler tho. Pass that "array" to another
function, wrapped in a struct to preserve its array-ness, and you
don't also pass over its size.


True - but where in the standard is this specific behavior
required for dynamically allocated objects? It's not news that
it's inappropriate to, for example, apply /sizeof/ to them. As we
tell the newbies (again and again): "It's the programmer's
responsibility to remember."
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #17
On Sat, 05 Jul 2003 08:13:29 -0500, in comp.lang.c , Morris Dovey
<mr*****@iedu.com> wrote:
My problem is that x knows neither the type of the element,
nor the number of them.
Not sure how you can say that, given that x was declared and
defined as a pointer to char (so that both programmer and
compiler know the type of the element);


we know that the variable is a pointer to a char. But it doesn't have
any elements (since its not an array), so we can't know the type of
them... *
and the exact number of
elements (known to the program, if not the compiler) is specified
in the malloc call.


but x doesn't cart that info around with it.

// the 12 is part of the definition of x
double x[12];

// not only is the 12 not part of x, but its wrong
double *x = malloc(12 * sizeof (int));

(yes, yes, I know the common CLC idiom, and agree with it)

* this is either tautology or psephology, I forget which... :-)
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #18

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

Similar topics

12
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...
97
by: s | last post by:
Can I do this: #define MYSTRING "ABC" .. .. .. char mychar = MYSTRING; .. .. ..
34
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...
6
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
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? ...
8
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...
4
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...
9
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
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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
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
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...

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.