views:

287

answers:

2

I have a 2d array grid made as int GRID[10][20]; What I want to do is remove the last row GRID[LAST][ALL] and insert a blank row at the start of the array. I tried Googleing this with no luck. Thanks

+1  A: 

Arrays are static constructs with fixed size. To get the sort of thing you're looking for (indexable contiguous storage with insertion and deletion), you should check out the STL vector container type.

Steve Gilham
Is is possible to shift the whole array?
Milo
STL vector would not be optimal for this, he probably wants a queue/deque.
Potatoswatter
Deque is only piecewise contiguous, so will not be a good match for something that expects to handle arrays.
Steve Gilham
multi-dimensional arrays are also not contiguous. He never said anything about needing that, anyway.
Potatoswatter
Worth noting that the other answer is relying on contiguous memory.
Steve Gilham
Huh? My C++ answers do not rely on contiguous memory. They will work with any container type. It sounds like what he wants is C anyway, which may be the right tool for the job… we don't know.
Potatoswatter
+3  A: 

This is NOT C++, this is C. You can do this:

memmove( GRID[1], GRID, sizeof GRID - sizeof GRID[0] ); // shift the array
bzero( GRID, sizeof GRID[0] ); // zero out the first row

If you were using C++, it would look like this:

GRID.pop_back(); // remove the last row
GRID.push_front( 10 ); // add an initial row

or this (which avoids allocating memory and dependency on size parameters):

rotate( GRID.begin(), GRID.end()-1, GRID.end() ); // shift the array
fill( GRID[0].begin(), GRID[0].end(), 0 ); // zero out the first row

And moreover in C++ you can use a queue instead of a vector, which is what you appear to want. In C++, however, a multi-dimensional array is an array of pointers to arrays, not a C-style array of arrays.

Potatoswatter
Neat piece of C code :)
the_drow