Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Trouble with passing an SDL_Rect array to a function


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 ChainedHollow   Members   -  Reputation: 158

Like
0Likes
Like

Posted 18 September 2012 - 08:40 PM

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!

Edited by ChainedHollow, 18 September 2012 - 08:43 PM.


Sponsor:

#2 kidman171   Members   -  Reputation: 498

Like
0Likes
Like

Posted 18 September 2012 - 09:50 PM

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[i].x << endl;
			cout << boxes[i].y << endl;
			cout << boxes[i].w << endl;
			cout << boxes[i].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, 18 September 2012 - 09:51 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS