0
dynamically allocate vector arrays
hello. i'm relatively new to programming (3 weeks). i was writing a program on visual c++. when i add more stuff in it, the program does not have any error but the debugger cannot run it. it says "Exception thrown at 0x00FC13E0 in tetris.exe: 0xC0000005: Access violation writing location 0x00FC4FE4." the number looks like an address, so i'm guessing my stack memory is overloading. But my program runs based on a 2D array. and i am not sure how to do that. is there a way to allocate 2d arrays to heap? or am i misunderstanding the error? thanks alot! (in case you can't see my reply)
4 Respuestas
+ 3
You are accessing your array out of bounds quite a lot, which is undefined behaviour and most likely the source of your error.
Given that 'n' is initially one and "positiony" is zero, in dropping() the following lines are undefined behaviour right from the start:
// line 129
pixel[positiony - 1][positionx] = 1; //upone
// line 133
pixel[positiony - 2][positionx] = 0;
Or, in control():
// line 241
pixel[positiony - 2][positionx] = 0;
This isn't even taking into account "positionx" and what happens in varying input scenarios. You'll have to think about how to avoid such invalid accesses throughout the game; consider using std::array<> or a sanitizer to catch these bugs early on.
As tips, global variables are quite hard to track over time, especially in larger programs. Try to avoid them. Also, the displayscreen() function can be simplified by a lot:
for (size_t i = 0; i < 25; ++i)
{
for (size_t j = 0; j < 10; ++j)
{
cout << pixel[i][j];
}
cout << '\n';
}
+ 5
First of all, there are of course ways to do that, for example using std::vector<>:
std::size_t width = ...;
std::size_t height = ...;
std::vector< std::vector< int > > foo( height, std::vector< int >( width ) );
Or using plain pointers and allocation:
int** foo = new int*[ height ];
for ( std::size_t i = 0; i < height; ++i ) {
foo[ i ] = new int[ width ]{};
}
However, I don't think your stack should be exhausted by a simple Tetris program. The error sounds more like you are accessing (writing) to a part of memory that does not belong to you, which can easily happen when accessing arrays out of bounds or mishandling pointers, for example. If it is not too much trouble, you could copy and paste the code into a playground project and link that here, so that we can have a look.
0
Shadow
thank you so much for helping
since i haven't finish the course of C++, the best i could do is display it using numbers. and my code is not finished
https://code.sololearn.com/coMf7US2y85K/?ref=app
0
Shadow
hello. thank you very much for taking time to read my program and reply. it is really informative, and helped me alot in learning. it also fixed my problem.
thanks again