So I was talking to my friend, helping her with a piece of code, and I always thought that arrays needed to be compile-time constants, as they are on the stack. But she said that her friend did this using this code:
#include <iostream.h>
#include <stdlib.h>
int main()
{
int value = ' ' ;
int sum = 0;
int count = 0;
cout<<"Please enter the total number of employees" <<endl;;
cin>> value;
int numbers[value];
cout<<"Now enter the employees corresponding salaries" <<endl;;
for (int k = 0; k < value; k++)
{
cin >> numbers[k];
}
}
They are using Dev-C++.
Is this code suppose to work? I assume not.
Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time.
Size of an array Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.
Run time Array initialization An array can also be initialized at runtime using scanf() function.
To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
Variable-length arrays are an extension in gcc
and g++
... so this won't work in every compiler.
For more information on gcc
's support for variable length arrays, you can see the documentation here.
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