Trouble with passing an SDL_Rect array to a function

Started by
0 comments, last by kidman171 11 years, 7 months ago
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?

Any advice, suggestions, or links to articles are much appreciated.
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!
Advertisement
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.

This topic is closed to new replies.

Advertisement