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...
An array must be a constant size. It cannot change.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With