Help with a pointer to array of pointers

Started by
7 comments, last by EWClay 11 years, 1 month ago

Hi everyone,

I have a function "load_tiles" that creates and returns a pointer to an array of pointers.

To fill up the array, I use a for loop. Initially it was something like for(int i = 0; i < TOTAL_TILES, i++); however now I want to transform it to use pointers to increment - mostly for the experience, but the performance bit too :)

The problem is that when I want to access an element in the array to set whether it's walkable or not, I get an "expression must have a pointer to class type" error.


c_Tile** tileArray = new c_Tile*[TOTAL_TILES];

for (c_Tile **ptr = tileArray; ptr < (tileArray + TOTAL_TILES); ptr++)
	{
		short tileType = -1;

		map >> tileType;

		if ( tileType >= 0 && tileType <= 12 )
		{
			*ptr = new c_Tile(x, y, tileType);

			if ( tileType >= 3 && tileType <= 12 )
			{
				**ptr->setWalkable(false); /*I know there's something wrong with this, but what?*/
				c_Entity_is_movable::unWalkables.push_back(*ptr);
			}
			else
				**ptr->setWalkable(true); /*I know there's something wrong with this, but what?*/
		}

		else
			SDL_Quit();

		x += TILE_WIDTH;

		if ( x >= LEVEL_WIDTH )
		{
			x = 0;
			y += TILE_HEIGHT;
		}
	}

I've tried also tried *ptr->setWalkable(true), but to no avail - I already know why it doesn't work but it seemed worth a try. To me, **ptr->foo() makes sense since it's a pointer to a pointer; so I dereference twice and should be at a c_Tile*.

Advertisement
If ptr is a c_Tile **, then **ptr is a c_Tile, not a pointer to a c_Tile. You're probably having operator precedence problems here. Try (*ptr)->setWalkable() or (**ptr).setWalkable().

I'm not sure that all this indirection and dynamic allocation is a good idea. Have you considered using an array (or container) of values? The "unWalkable" list (or set) could be composed of (pairs of) indices, which may make it easier to use:

 
std::vector<std::pair<int, int>> unwalkableIndices;
std::vector<Tile> tiles;
tiles.reserve(TOTAL_TILES);
for (int y = 0 ; y < LEVEL_HEIGHT ; ++y ) {
    for (int x = 0 ; x < LEVEL_WIDTH ; ++x ) {
        short tileType;
        if(map >> tileType) {
            if ( tileType >= 0 && tileType <= 12 ) {
                int tileX = x * TILE_WIDTH;
                int tileY = y * TILE_HEIGHT;
                // Why set the value after the fact when you can pass it to the constructor?
                bool walkable = tileType < 3;
                tiles.push_back(Tile(tileX, tileY, tileType, walkable));
                if (!walkable ) {
                    // Might be easier to store world co-ordinates, depending on what this gets used for
                    unwalkableIndices.push_back(std::make_pair(x, y));
                }
            } else {
                // Error handling - tile type unknown
            }
        } else {
            // Error handling - failed to read tile type
        }
    }
}

You could also consider dropping the "walkable" member of the Tile type, as it appears it can be safely inferred from the type:

bool isWalkable(const Tile &tile) {
     return tile.type() < 3;
}

You might also consider using named constants or enumeration values for your tile types, rather than magic numbers:

enum TileType {
     // Walkable
    Grass,
    Gravel,
    Carpet,
    // Not walkable
    HotCoals,
    // ...
    MoltenLava,
};
 
 
enum {
    MaxWalkable = Carpet.
    MaxTileType = MoltenLava
}
 
 
bool isWalkable(TileType type) {
     return type <= MaxWalkable;
}

It's fine to do this for the experience, but I doubt there would be any difference in performance. And now you've got less readable code!

I actually didn't see the part apart converting it to pointers.

... but the performance bit too

Pointers are not necessarily going to help performance. Indirection and dynamic allocation are usually recommended against when trying to optimise code (where possible).

I actually didn't see the part apart converting it to pointers.


... but the performance bit too

Pointers are not necessarily going to help performance. Indirection and dynamic allocation are usually recommended against when trying to optimise code (where possible).

It sounds like it was always an array of pointers, but he changed the iteration from using indices to using pointers. That can be faster, sometimes, but standard containers and iterators will do the same thing safer.

If ptr is a c_Tile **, then **ptr is a c_Tile, not a pointer to a c_Tile. You're probably having operator precedence problems here. Try (*ptr)->setWalkable() or (**ptr).setWalkable().

Ah! This was my problem. So I'm guessing that this is another little quirk about c++ I'll have to get used to...

@rip-off, those are some great suggestions - this is just a small project that I don't expect to go far; after (too) many memory errors because of unnecessary new() and delete() I've learned a lot of what not to do, and plan to make use of safer methods in the future - for now I'm going to try to push through with what I have :p

Pointers are generally slower than array indexing, because the compiler can reason about aliasing (whether or not two pointer point to the same thing) easier with arrays indexes, and will therefore be more aggressive at optimizing.

Pointers are generally slower than array indexing, because the compiler can reason about aliasing (whether or not two pointer point to the same thing) easier with arrays indexes, and will therefore be more aggressive at optimizing.

If you use an index to address a vector, it will have to calculate the address using integer multiplication and a pointer offset every time, because unless you have __restrict on everything it doesn't know whether the start address has changed.

Compilers are perfectly well able to reason about pointers.

They will generally do a good job with vector iterators too, because iterator implementations are written with performance in mind.

One thing is sure, though: the way you iterate through a vector is very unlikely to be significant when looking at the bigger picture.

This topic is closed to new replies.

Advertisement