0

Given that user input is taken at runtime but array is created during compile time. How and why does this piece of code work?

#include <iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    int arr[n]; //Why can I use this statement to create an array?
}
0

1 Answer 1

1

It's a non-standard extension, supported by gcc and clang.

It works by allocating space on the stack at the point the array is declared, a bit like alloca.

The memory allocated is automatically freed (by adjusting the stack pointer) when the function returns (or arr goes out of scope).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.