int array

M

Matthew Jakeman

Hi, if i define an int array globally as follows :

int test[] ;

Is it possible to set the size of this array inside a function later in the
code ?

TIA
Matt
 
R

Rob van der Leek

Mark A. said:
Hi, if i define an int array globally as follows :

int test[] ;

Is it possible to set the size of this array inside a function later
in
the code ?

No.

If the size of the array is only known at run-time, you need to allocate
memory for the array at run-time. This is called "dynamic allocation"
(if you specify the array size at compile-time (e.g. int test[3]) it is
called "static allocation").

I advice you to consult a C book on these topics.
Regards,
 
C

Christopher Benson-Manica

Rob van der Leek said:
If the size of the array is only known at run-time, you need to allocate
memory for the array at run-time. This is called "dynamic allocation"
(if you specify the array size at compile-time (e.g. int test[3]) it is
called "static allocation").

I believe the size of OP's array is known at compile time; the issue
is that there is no way to determine the size of an array outside the
scope in which it is declared, which seems to be what OP wants to do.
 
D

Dan Pop

In said:
Hi, if i define an int array globally as follows :
^^^^^^
int test[] ;

Is it possible to set the size of this array inside a function later in the
code ?

An object *definition* is a declaration that also allocates memory for
that object. How can the compiler allocate memory for test[] without
knowing its size?

What you can do is *declaring* test[] as a global without specifying its
size:

extern int test[];

and define it elsewhere in your code. Note that you cannot use
sizeof test until the compiler has seen the actual definition or a
declaration also specifying the size.

Dan
 
C

CBFalconer

Rob said:
Mark said:
Matthew Jakeman said:
Hi, if i define an int array globally as follows :

int test[] ;

Is it possible to set the size of this array inside a function
later in the code ?

No.

If the size of the array is only known at run-time, you need to
allocate memory for the array at run-time. This is called
"dynamic allocation" (if you specify the array size at compile-
time (e.g. int test[3]) it is called "static allocation").

I advice you to consult a C book on these topics.

Note that Mark replied to a query that dealt with 'globally'
defined arrays, which can be loosely interpreted to mean
statically allocated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top