Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a statically-allocated variable-size array works in C++ ?

#include <iostream>

    using namespace std;

    int main(int argc, const char * argv[])
    {

        int size;
        cin >> size;
        int myArray[size]; //this shouldn't compile , right ? 

        return 0;
    }

I thought this wouldn't compile, but it does actually (using the g++ command).

What I found out later is that GCC actually allows variable-size arrays even if by standard C++ doesn't support variable-size arrays, Which is weird ! Because I hear everyone saying that the only way to create a variable-size array is to use dynamic allocation like int* array = new int[size]; or better std::vector. I thought GCC wouldn't allow that piece of code !

Anyway, My theoretical question is, the myArray array is allocated in the heap or stack area ?

like image 785
Zakaria Braksa Avatar asked Aug 14 '26 00:08

Zakaria Braksa


1 Answers

That is an extension on the compiler side. How does it work? Well, it works only to some extent.

The implementation basically moves the stack pointer a quantity that is dependent on the size of the array, and calls the memory in the middle by the name of the array. It only works to some extent because in VLAs the size is not an integral part of the type, which means that many constructs that can be used on regular arrays cannot be done with this type, like for example passing the array to a template by reference... sizeof is usually supplied but implemented as a runtime construct.

like image 68
David Rodríguez - dribeas Avatar answered Aug 19 '26 14:08

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!