Public Group

Acessing a single array in a two-dimensional array

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

Recommended Posts

Hey all This is probably a pretty stupid question, but If I have the 2d array map [ROWS][COLUMNS], how would I access just the columns portion without including information for the rows? Specifically, I want to be able to do something like this: if( Keys[SDLK_LEFT] && (map /*dont know what to de here*/[you.x/WIDTH]) != 2 ) Thanks in advance!

Share on other sites
The row/column parts of a 2d array do not hold information individually. That is, for every row you have, you will have a corresponding number of values in each column.

i.e. an array with 3 rows and 3 columns can hold 9 values: [1][1] [1][2] [1][3] [2][1] etc. of whatever data type you want.

So if you want to check column 2, there will be three values, one for each row ([1][2] [2][2] [3][2]). And you have to specify the row you want the value for. If you want all of the values for column 2 then you should use a loop to extract them individually.

Perhaps a 2d array is not what you wanted and maybe 2 1d arrays might better suit your needs?

If you need clarification or further examples, let me know.

Hope it helps.

Share on other sites
Ah, I see now, I've been visualizing it wrong the whole time.

Thanks alot!

Share on other sites
I think you're going at this the wrong way. In order to get to COLUMN, you have to specify a ROW first. If you're trying to avoid double indexing, and if you know which ROW you want to work with, you could copy a row over to a pointer of the type your map is:

int map[2][5];int *pRow = map[n];if( (Keys[SDLK_LEFT] && pRow[n]) != 2 )

Does that work out for you?

- xeddiex

Share on other sites
I see what you're getting at there too, thank you both!

Edit:
Just as kinda a final clarification, I'm making a tilemap engine, and am right now struggling on the collision detection. If anyone has any suggestions on a better way to do collision, please don't heisitate to chime in ;)

[Edited by - Craig M on March 1, 2006 1:45:51 AM]

Share on other sites
Well, with your 2D array, you could do something as simple as this:

#define ROWS 5#define COLS 20#define WALL 1int main(int argc, char **argv){	int map[ROWS][COLS] = {		{1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},		{1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},		{1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},		{1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},		{1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},		{1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1},		{1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0},		{1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0}};	if ( map[Player.xPos][Player.yPos] != WALL )		;// Player not colliding on walls	return 0;}

- xeddiex

1. 1
Rutin
19
2. 2
3. 3
JoeJ
15
4. 4
5. 5

• 18
• 19
• 10
• 13
• 17
• Forum Statistics

• Total Topics
631694
• Total Posts
3001751
×