C++ Multidimensional array in existing memory

前端 未结 4 2101
既然无缘
既然无缘 2020-12-19 20:58

(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 funct

4条回答
  •  佛祖请我去吃肉
    2020-12-19 21:37

    For anyone trying to achieve the same, I 've created a variadit template function that would create a n-dimension array in existing memory:

    template  size_t CreateArrayAtMemory(void*, size_t bs)
    {
        return bs*sizeof(T);
    }
    
    template 
    size_t CreateArrayAtMemory(void* p, size_t bs, Args ... args)
    {
        size_t R = 0;
        size_t PS = sizeof(void*);
        char* P = (char*)p;
        char* P0 = (char*)p;
    
        size_t BytesForAllPointers = bs*PS;
        R = BytesForAllPointers;
    
        char* pos = P0 + BytesForAllPointers;
        for (size_t i = 0; i < bs; i++)
        {
            char** pp = (char**)P;
            if (p)
                *pp = pos;
            size_t RLD = CreateArrayAtMemory(p ? pos : nullptr, args ...);
            P += PS;
            R += RLD;
            pos += RLD;
        }
        return R;
    }
    

    Usage:

    Create a 2x3x4 char array:

    int j = 0;
    size_t n3 = CreateArrayAtMemory(nullptr,2,3,4);
    std::vector a3(n3);
    char*** f3 = (char***)a3.data();
    CreateArrayAtMemory(f3,2,3,4);
    for (int i1 = 0; i1 < 2; i1++)
    {
        for (int i2 = 0; i2 < 3; i2++)
        {
            for (int i3 = 0; i3 < 4; i3++)
            {
                f3[i1][i2][i3] = j++;
            }
        }
    }
    

提交回复
热议问题