[Solved] I cannot understand why this code gives a segmentation fault. Please, can anyone tell me where have I allocated a memory which cannot be used [closed]


Whoops!

Looks like you’re trying to create a variable sized array (which doesn’t exist… kinda) with an undefined variable (which can be anything the system wants it to be).

Use pointers instead, and let the user fill the variable before creating the array:

int n;
std::cin >> n;
int* a = new int[n];

Or use the magic C++ vectors, since you’re including them. They offer many more features than plain pointers like dynamic allocation and some newer methods of type-safety, along with multiple in-out methods like LIFO and FIFO:

int n;
std::cin >> n;
std::vector<int> a(n);

3

solved I cannot understand why this code gives a segmentation fault. Please, can anyone tell me where have I allocated a memory which cannot be used [closed]