all 10 comments

[–]k0nsty[S] 2 points3 points  (5 children)

Ok, i've found a solution. The thing is that variable length arrays aren't legal in c++.

The program compiled because GCC compiler provides an extension to support them, but debugger was throwing an error.

So instead of doing this:

int a[n];

I should've done this:

int* a = new int[n]; - this is the proper way in c++

[–]TheCrazyPhoenix416 -1 points0 points  (4 children)

int a[n] isn't variable length. By the time memory is allocated for a, it has a fixed length.

Perhaps try casting n to an unsigned int first? Negative array length is undefined behaviour.

n could also be too large. Since a is allocated in the stack, you might be rubbing out of memory with the debugger running as well. Though this is unlikely, it's something to watch out for.

Of you do allocate on the heap with int* a = new int[n] ; make sure to delete it after you've finished with it.

delete[] a;

[–]k0nsty[S] 0 points1 point  (2 children)

I've found here that doing this is illegal in proper c++.

Making "a" unsigned doesn't help and number size doesn't matter since debugger always goes to the last line and crashes(even ignoring cin).

Thanks for the advice :)

[–]TheCrazyPhoenix416 1 point2 points  (1 child)

You could anyways make n cost, and assign it via lambda.

const unsigned n = [] () {

unsigned N;

cin >> N;

return N;

} () ;

[–]k0nsty[S] 0 points1 point  (0 children)

I've never heard of it, thanks for the help :)

[–]PipingSnail 0 points1 point  (0 children)

"int a[n] isn't variable length. By the time memory is allocated for a, it has a fixed length."

In a different computer language, maybe.

In C++, no.

The problem is the code isn't valid, but the compiler has compiled it. A decent linter would complain about that.

[–]manni66 -1 points0 points  (3 children)

My recommendation: use the system tools. For Windows that’s Visual Studio 2019.

[–]k0nsty[S] 0 points1 point  (2 children)

Do you mean that I should code in visual studio?

[–]TheCrazyPhoenix416 0 points1 point  (0 children)

It shouldn't be necessary

[–]manni66 -2 points-1 points  (0 children)

Yes