本文介绍了将多维数组放入一维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。我正在用C ++写一个简单的应用程序,但遇到以下问题:
我想使用二维数组指定对象的位置(x和y坐标)。但是当我创建这样的数组时,访问它时会遇到很多访问冲突问题。我不太确定违规的来源,但是我认为我的堆栈不够大,应该使用指针。但是当我搜索在堆中使用多维数组并指向它的解决方案时,这些解决方案对我来说太复杂了。

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] = ' ';
    }
}

但这是不对的,因为该字符是在位置y + x * y上没有确切指定(因为y + y * x指向相同位置)
但是我很确定,有一种方法可以做到这一点。也许我是错的,所以告诉我:D
在这种情况下,使用多维数组的解决方案会很棒!

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 :DIn this case, a solution to use multidimensional array would be great!

推荐答案

您不希望 y + x * y ,而是希望 y * SCREEN_WIDTH + x 。也就是说,一个二维数组声明为:

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] = ' ';

这篇关于将多维数组放入一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:11