现有内存中的C ++多维数组 [英] C++ Multidimensional array in existing memory

查看:66
本文介绍了现有内存中的C ++多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这不是指的是固定大小,问题不是要了解指针的存储方式,而是如果编译器可以自动执行手动功能.

(This is not a duplicate of this or this that refer to fixed sizes, the issue is not to understand how pointers are stored, but if the compiler can automate the manual function).

基于此SO问题存储多维数组

// These arrays are the same
int array1[3][2] = {{0, 1}, {2, 3}, {4, 5}}; 
int array2[6] = { 0, 1, 2, 3, 4, 5 }; 

但是我试图在预分配的内存中创建一个二维浮点数组:

However I'm trying to create a 2 dimension array of floats in pre-allocated memory:

float a[5][10] 
float b[50]; // should be same memory

然后我正在尝试:

vector<char> x(1000);
float** a = (float**)x.data();
a[0][1] = 5;

上面的代码崩溃,显然是因为编译器不像第一个示例中的编译器级别的已知数组那样,不知道要在内存中分配数组的数组大小.

The above code crashes, obviously because the compiler does not know the size of the array to allocate it in memory like in the compiler-level known array in the first example.

有没有一种方法可以告诉编译器在不手动计算指针的情况下(例如,通过手动移动索引并调用new放置)在顺序存储器中分配多维数组?

Is there a way to tell the compiler to allocate a multi dimensional array in sequential memory without manually calculating the pointers (say, by manually shifting the index and calling placement new for example)?

当前,我正在手动进行操作,例如:

Currently, I'm doing it manually, for example:

template <typename T> size_t CreateBuffersInMemory(char* p,int n,int BufferSize)
{
    // ib = T** to store the data
    int ty = sizeof(T);

    int ReqArraysBytes = n * sizeof(void*);
    int ReqT = ReqArraysBytes * (ty*BufferSize);
    if (!p)
        return ReqT;

    memset(p, 0, ReqT);
    ib = (T**)p;
    p += n * sizeof(void*);
    for (int i = 0; i < n; i++)
    {
        ib[i] = (T*)p;
        p += ty*BufferSize;
    }
    return ReqT;
}

非常感谢.

推荐答案

要将T[rows][cols]数组分配为一维数组,请分配T[rows * cols].

To allocate T[rows][cols] array as a one-dimensional array allocate T[rows * cols].

要访问该一维数组的元素[i][j],可以执行p[i * cols + j].

To access element [i][j] of that one-dimensional array you can do p[i * cols + j].

示例:

template<class T>
struct Array2d {
    T* elements_;
    unsigned columns_;

    Array2d(unsigned rows, unsigned columns)
        : elements_(new T[rows * columns]{}) // Allocate and value-initialize.
        , columns_(columns)
    {}

    T* operator[](unsigned row) {
        return elements_ + row * columns_;
    }

    // TODO: Implement the special member functions.
};

int main() {
    Array2d<int> a(5, 10);
    a[3][1] = 0;
}

这篇关于现有内存中的C ++多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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