在C ++中访问1D数组作为2D数组 [英] Access a 1D array as a 2D array in C++

查看:165
本文介绍了在C ++中访问1D数组作为2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我困扰了一段时间。很多时候,我发现自己做了一个大的缓冲区来保存最大的数据量。这有助于我避免每次下一个数据集的大小改变时动态分配和释放缓冲区。

This has bothered me for a while. A lot of times I find myself making a large buffer to hold a "maximum" amount of data. This helps me avoid dynamically allocating and deallocating a buffer each time the size of the next data set changes.

例如,我有一个数组,它的实际有用的大小太大,但我知道有用的数据的长度。

For instance say I have an array that is way too large for its actual useful size, but I know the length of the useful data.

int amountOfData = 9;
char data1D[100] = some data that is only 9 bytes long stored in a 100 byte array

假设我有一个算法,我想运行这个数据集,使用二维数组索引。所以我想要能够访问数据如下:

Lets say I have an algorithm I want to run on this data set that uses 2D array indexing. So I want to be able to access the data as follows:

cout << "I am accessing this data as a 2D array: " << data1D[0][1] << endl;

我们知道这个算法我知道2D数组的xlength和ylength是:

Lets say for this algorithm I know that the xlength and ylength of the 2D array are going to be:

int xlength = 3;
int ylength = 3;

。然而,对于下一次迭代,长度可以不同。也就是说。它们可以是 xlength = 4 ylength = 4 给定 amountOfData = 16

for this iteration, because amountOfData = 9. However, the lengths may be different for the next iteration. Ie. they could be xlength = 4 and ylength = 4 given amountOfData = 16.

我想做一些类型的转换,允许我使用2D数组索引投射1D数组。我知道我的初始1D长度有多长,它告诉我我的2D xlength ylength 有多长,所以这个应该很容易做到不使用 new malloc ,只要最初的100个字节足够长,数据集给我。

I want to do some kind of casting that allows me cast the 1D array using 2D array indexing. I know how long my initial 1D length is, which tells me how long my 2D xlength and ylength are, so this should be easy to do without using new or malloc as long as the initial 100 bytes is long enough to hold any useful data set to me.

我意识到:

char** data2d = (char**) data1D;

无法工作,因为编译器不知道第二个维度的大小。但我会知道它在运行时是什么!

will not work because the compiler doesn't know the size of the second dimension. But I will know what it is at runtime!

这是什么的根本原因是什么?
是否有任何解决方法?
我缺少什么?

What is the underlying reason for this being the way it is? Are there any workarounds? Am I missing anything?

推荐答案

一旦你只知道运行时数组的长度,更好地解决这个问题,不使用2D数组,而是通过使用函数来模拟它。例如,在C:

Once you only know the length of your array at runtime, I guess it is better to solve this problem not using an 2D array, but emulating it by using functions. For example, in C:

char data1D[1000] = {0};

unsigned int getElement(unsigned int x, unsigned int y, 
            unsigned int xMax, unsigned int yMax)
{
  // Do some error tests
  return ((unsigned int *) data1D)[x*xMax + y];
}

这篇关于在C ++中访问1D数组作为2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆