Archived

This topic is now archived and is closed to further replies.

Bong

Passing 2D Arrays Fast

Recommended Posts

Bong    122
Hey, does anybody know the fastest way to pass a 2d array of structures to a function? - Bong, James Bong

Share this post


Link to post
Share on other sites
a person    118

  
return_type function_name(struct_type **arrayname, otherargs,)
{
// code here

}
//or is using linear 2d arrays

return_type function_name(struct_type *arrayname, otherargs,)
{
// code here

}


you cant get faster then just passing the address for the array.

Share this post


Link to post
Share on other sites
Bong    122
Yeah, I guess that''d work the fastest, but my compiler gives me an error whenever I try to return a pointer to a 2d array. This is my function:

Tile** Map::GetTiles()
{
return TileMap;
}

TileMap is delcared as:

Tile TileMap[256][256];

However, I get an error saying "cannot convert Tile(*)[256] to Tile**

Do I have to return TileMap as a Tile*[256]?
Will that slow my program down any?

- Bong, James Bong

Share this post


Link to post
Share on other sites
Bong    122
Now the compiler gives me an error saying "cannot convert Tile* to Tile**"

I tried changing it to

return &(&(TileMap[0][0]));

but it gives me an error saying "not a 1value"

- Bong, James Bong

Share this post


Link to post
Share on other sites
Kippesoep    892
The problem is that you''re trying to convert to an array of arrays to an array of pointers, which seems to work the same, but really isn''t. Anyway, you can pass it along as a linear array:


  
void fill128x256 (int *array)
{
for (int y = 0; y < 128; y++)
{
for (int x = 0; x < 256; x++)
{
array [y * 256 + x] = rand ();
}
}
}

void useless ()
{
int myarray [128][256];
fill128x256 (&(myarray [0][0]));
}


Also, take a look at this thread, in which I have also posted a class to encapsulate this behaviour.

Share this post


Link to post
Share on other sites