• 11
• 9
• 10
• 9
• 10

Trouble with passing an SDL_Rect array to a function

This topic is 2042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I'm having trouble understanding passing an array to a function. I've been looking on google and I read an article on pointers but I still just don't get this part, so I'm hoping you all can help.

What I have is 2 classes for my Tetris game, a block class and a board class.
The block class has an array SDL_Rect blockBoxes[4]; which holds the collisions boxes of each block in a shape.
I'm wanting to pass this to one of the board class's functions, for example:

Board::set_board(SDL_Rect array[]) { }; // the functions

Board game_field(); // the object

game_field.set_board(blockBoxes);
.
.
.
etc.

How can I accomplish this and access the members of the array within the function?

This is my first SDL game, and 2nd game total. I usually just give up on this topic and just make things I need global but I want to finally learn and understand this while Im still practicing. Thank you again! Edited by ChainedHollow

Share on other sites
Maybe you should consider using vectors instead of arrays. Consider this example:

 class Board { public: void set_board(vector<SDL_Rect> boxes) { for(int i = 0; i < boxes.size(); ++i) { cout << boxes.x << endl; cout << boxes.y << endl; cout << boxes.w << endl; cout << boxes.h << endl; } } }; int main() { Board game_field; SDL_Rect sr1; sr1.x = 10; sr1.y = 20; sr1.w = 30; sr1.h = 40; SDL_Rect sr2; sr2.x = 50; sr2.y = 60; sr2.w = 70; sr2.h = 80; vector<SDL_Rect> blockBoxes; blockBoxes.push_back(sr1); blockBoxes.push_back(sr2); game_field.set_board(blockBoxes); return 0; } 

This prints out:
 10 20 30 40 50 60 70 80 
By using a vector, you have the advantage of a dynamic-length container and it also remembers its size, making it easy to pass data around. Edited by kidman171