Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays with a size determined at run time, is this valid in C++?

Tags:

c++

arrays

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.

like image 335
jValdron Avatar asked Dec 02 '11 20:12

jValdron


People also ask

Can the size of an array be declared at runtime in C?

Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time.

Can we give size of array 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.

How do you declare an array in runtime?

Run time Array initialization An array can also be initialized at runtime using scanf() function.

How does C know the size of an array?

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.


1 Answers

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.

like image 113
Jason Avatar answered Sep 23 '22 21:09

Jason