0

I'm writing a game in cocos2dx, and i'm trying to refactor a method thats gets called a few times. I want to return a two dimensional array from an enum of vehicletype

How can i get something like the following to work??

int Vehicle::getVehicle(VehicleTypes vehicletypes)
{

int vehicle[8][8] = {0};

switch (vehicleType) {
    case Car:
            // --- ARRAY 1 ------

            vehicle = {
                { 0,0,0,0,0,0,0,0 },
                { 0,0,1,2,5,8,0,0 },
                { 0,0,5,3,4,5,0,0 },
                { 0,0,0,6,0,7,0,0 },
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
            };
            break;
    case Bus:
        {
            // --- ARRAY 2 ------

            Vehicle = {
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,1,2,0,0 },
                { 0,0,3,4,5,0,0,0 },
                { 0,0,6,8,7,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
                { 0,0,0,0,0,0,0,0 },
            };
            break;
        }
    default:
        break;
    }

return vehicle;
}

Thanks

A Devanney
  • 63
  • 8

2 Answers2

1
typedef const int (*matrix_ptr)[8];

Demo: http://ideone.com/i1Tc2

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

Why are you using arrays? You should use one of the STL containers such as a vector. Either way, a 2D int array in C++ is basically a pointer to a pointer of int's. Either the caller of the function needs to supply an allocated 2D array on the heap or stack and pass it as a in/out argument or have the "callee" (this function) allocate a 2D array on the heap and pass it back to the caller. If it's the latter case, then the caller is now responsible for deallocating the memory.

user1040229
  • 491
  • 6
  • 18
  • 1
    No, a "2D int array" is an array that decays to a pointer to a one-dimensional array of ints. `int[n][m]` won't decay to `int**`. – R. Martinho Fernandes Jan 30 '12 at 22:45
  • Well, up until now i've just used c/c++ (what i know!!) in this development, because i'm using cocos2dx. I'm developing in visual studio getting things to work, then moving everything thing to xcode on the mac and pushing to the iphone. Will STL containers still be compatable on the mac? maybe its time to find out cheers – A Devanney Jan 31 '12 at 10:38