简体   繁体   English

需要从3d阵列到1d阵列的memcpy解释

[英]Need explanation of memcpy from 3d array to 1d array

Why can't I use memcpy to flatten 3d dynamic allocated array to 1d array? 为什么不能使用memcpy将3d动态分配的数组展平为1d数组?

What is the difference between storage of 3d and 1d dynamic allocated array? 存储3d和1d动态分配数组有什么区别?

Thanks for your attention.I would be really appreciate if you could give some explanation/links/books. 感谢您的关注。如果您能给出一些解释/链接/书籍,我们将不胜感激。

#include<iostream>
using namespace std;
int main()
{               
        float ***b;
        int i,j,k;
        int ntab=26,ncrss=3,nsubs=1;
        b=(float***)malloc(ntab*ncrss*nsubs*sizeof(float));
        for(i=0;i<nsubs;i++)
        {
                b[i]=(float**)malloc(ncrss*ntab*sizeof(float));
                for(j=0;j<ncrss;j++)
                {
                        b[i][j]=(float*)malloc(ntab*sizeof(float));
                }
        }
        for(i=0;i<nsubs;i++)
                for(j=0;j<ncrss;j++)
                        for(k=0;k<ntab;k++)
                                b[i][j][k]=k;
        for(i=0;i<nsubs;i++)
                for(j=0;j<ncrss;j++)
                        for(k=0;k<ntab;k++)
                                printf("b[%d][%d][%d]=%f\n",i,j,k,b[i][j][k]);
        float *a;
        a=(float*)malloc(ntab*ncrss*nsubs*sizeof(float));
        //memcpy(a,b,ntab*ncrss*nsubs*sizeof(float));
        for(i=0;i<nsubs;i++)
        {
                const int index1=i*ncrss*ntab;
                for(j=0;j<ncrss;j++)
                {
                        const int index2=j*ntab+index1;
                        for(k=0;k<ntab;k++)
                        {
                                a[index2]=b[i][j][k];
                        }
                }
        }
        for(i=0;i<ntab*ncrss*nsubs;i++)
                printf("a[%d]=%f\n",i,a[i]);

        return 0;
}

You have multiple calls to malloc, which means your 3d array is not contiguous in memory. 您有多个对malloc的调用,这意味着您的3d数组在内存中不连续。 Thus memcpy cannot handle it all at once. 因此,memcpy无法一次处理所有操作。

If you had allocated your 3d array in a contiguous fashion: 如果您以连续方式分配了3d数组:

malloc(sizeof(float) * ntab * ncrss * nsubs)

then memcpy would work. 那么memcpy就可以了。

The 3d dynamic array which was constructed in the code snippet is a pointer to an array of pointers to arrays of pointers to arrays of values. 在代码片段中构造的3d动态数组是一个指向指针数组的指针,该指针数组指向值数组的指针。

When memcpy is used with b as the source, it means the array to which b points to is copied. 当memcpy与b一起用作源时,表示b指向的数组被复制。 It means the array of pointers to arrays of pointers to arrays of values is copied. 这意味着复制了指向值数组的指针数组的指针数组。

In this case, the line 在这种情况下,

//memcpy(a,b,ntab*ncrss*nsubs*sizeof(float));

copies ntab*ncrss*nsubs*sizeof(float) bytes starting from the address to which b points to. 从b指向的地址开始复制ntab*ncrss*nsubs*sizeof(float)个字节。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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