Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array size and const [duplicate]

Tags:

c++

arrays

Possible Duplicate:
initialize array size from another array value

in C++

const int a[]={1,2,3,4,5}; 
int b[a[2]]; 

int main()
{
    return 0;
} 

The code is giving error in line 2; However, if it is something like below it gives no error after compilation:

const int a=3; 
int b[a]; 

int main()
{
    return 0;
} 

Why is that? however if i define array b inside main it is alright in both the cases...

like image 472
algo-geeks Avatar asked Jan 18 '11 03:01

algo-geeks


People also ask

Does array size have to be constant C++?

An array must be a constant size. It cannot change.

Can an array be a const?

Arrays are Not Constants It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

Is array size fixed in Java?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Can you modify a const array in C?

You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable. That means, a const qualified variable must not be assigned to in any way during the run of a program.


2 Answers

Because in C++ array sizes must be constant expressions, not just constant data. Array data, even though const, is not a constant expression.

Second version IS a constant expression.

like image 91
Edward Strange Avatar answered Sep 29 '22 08:09

Edward Strange


It looks like you want to make a variable-sized array. To do this, one must use pointers.

POINTERS

Normally, you would declare an array like this:

char a[4];

An array must be a constant size. It cannot change. How can we make the size variable? Like this.

char* a = new char[length];

What does this do? Normally, when you declare an array of a specific size, it is declared on the stack. What this code does, however, is instead allocate memory on the heap.

char a[4]; // This is created at compile time
char* a = new char[length]; // This is created at run time

You create a pointer to an address where you can declare and assign values to your array, all in a safe memory space.

like image 36
Charles Ray Avatar answered Sep 29 '22 08:09

Charles Ray