简体   繁体   中英

Put a multidimensional array into a one-dimensional array

I've got a question. I'm writing a simple application in C++ and I have the following problem: I want to use a two-dimensional array to specify the position of an object (x and y coordinates). But when I created such an array, I got many access violation problems, when I accessed it. I'm not pretty sure, where that violations came from, but I think, my stack is not big enough and I shuld use pointers. But when I searched for a solution to use a multidimensional array in heap and point on it, the solutions where too complicated for me.

So I remembered there's a way to use a "normal" one-dimensional array as an multidimensional array. But I do not remember exactly, how I can access it the right way. I declared it this way:

char array [SCREEN_HEIGHT * SCREEN_WIDTH];

Then I tried to fill it this way:

for(int y = 0; y < SCREEN_HEIGHT; y++) {
    for(int x = 0; x < SCREEN_WIDTH; x++) {
        array [y + x * y] = ' ';
    }
}

But this is not right, because the char that is at position y + x * y is not exactly specified (because y + y * x points to the same position) But I am pretty sure, there was a way to do this. Maybe I am wrong, so tell it to me :D In this case, a solution to use multidimensional array would be great!

You don't want y + x*y , you want y * SCREEN_WIDTH + x . That said, a 2D array declared as:

char array[SCREEN_HEIGHT][SCREEN_WIDTH];

Has exactly the same memory layout, and you could just access it directly the way you want:

array[y][x] = ' ';
char array2D[ROW_COUNT][COL_COUNT] = { {...} };
char array1D[ROW_COUNT * COL_COUNT];

for (int row = 0; row < ROW_COUNT; row++)
{
    for (int col = 0; col < COL_COUNT; col++)
    {
        array1D[row * COL_COUNT + col] = array2D[row][col];
    }
}

You access the correct element for your 1D array by taking "current row * total columns + current column," or vice-versa if you're looping through columns first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM