Namratha
Namratha

Reputation: 16790

statically define an array based on a variable value C/C++

I want to define a 2D array statically. The size of the array is determined by a variable. How do I do this? I do not want to dynamically define the array. I heard that there is a way to do this.

Upvotes: 1

Views: 512

Answers (5)

Alok Save
Alok Save

Reputation: 206546

Answer is No You Cannot in C++.
Dimensions of the array must be known at compile time.

int my_array[6][7];   // okay  
int my_array[H][7];   // ISO C++ forbids variable length array 
int my_array[6][W];   // ISO C++ forbids variable length array 
int my_array[H][W];   // ISO C++ forbids variable length array 

Some compilers do support Variable Length Arrays(VLA) through their own extension but VLA are not defined in the C++ standard, hence using VLA will be non conforming to C++ standard.

VLA's were introduced in C99 C standard. C++ was branched out from C standard of C98. By the time C introduced VLA, C++ already had Vectors and had no need to support or encourage VLA. Hence, VLA was never formally accepted in the C++ Standard, some C++ compiler still support VLA through compiler extensions.

Since, you tagged your Q C as well as C++, to summarize the answer:

In C99 & versions after that : You Can  
Versions before C99: You Can't
In C++(Any version): You can(through compiler extensions) but You should'nt

Here is the legendary C++ FAQ which explains everything about arrays.
I learned a lot from it. :)

Upvotes: 3

Necrolis
Necrolis

Reputation: 26171

This depends where and when the variable is initialized. If its something done at compile time you can use templates to get it done: template </* args */> struct ConstExpr{enum{value = /* math goes here */};};, else its impossible without selfmodifying code(and I'm pretty sure this is gonna very dangerous, because you'll need to alter the PE so you can somehow get your allocated space change before its virtualized).

Upvotes: 0

Michael Dorgan
Michael Dorgan

Reputation: 12515

If one of the dimensions of the array is variable, then the size must be variable, then it must be dynamically sized - or sized in such a way that the the array is statically sized larger than the largest value that the variable could be.

Upvotes: 1

Etienne de Martel
Etienne de Martel

Reputation: 36851

By "variable", I assume you're talking about a non-constant value.

In C99, yes:

int size = ...;
int array[size][size];

In C++, you can't. The alternative is to use pointers and dynamic allocation (or better yet, vectors).

In C versions prior to C99, it's also impossible. Use malloc().

Upvotes: 0

koool
koool

Reputation: 15517

I dont think so you can statically define it! However you can use vector but underneath it too does dynamic allocation for you

Upvotes: 1

Related Questions