A是2d数组,数据是1d数组

double **A, *data;


全尺寸为9222,
内存分配:

A = (double **)malloc((fullsize)*sizeof(double *));         //allocate memory dynamically for matrix A
for (i = 0; i < fullsize; i++)
    A[i] = (double *)malloc((2 * fullsize)*sizeof(double));

data = (double *)malloc((fullsize*fullsize)*sizeof(double *));


转换逻辑:

{
    for (int n = 0; n<fullsize; n++)
    for (int m = 0; m<fullsize; m++)
    {
        data[n*fullsize + m] = A[n][m];
    }
}


错误日志:

The thread 0xad80 has exited with code 0 (0x0).
Unhandled exception at 0x00F5E6E9 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x69E65000.

The program '[50964] ConsoleApplication1.exe' has exited with code 0 (0x0).

最佳答案

您正在使用data指针的大小分配double

data = (double *)malloc((fullsize*fullsize)*sizeof(double *));
//                                                        ^


应该使用sizeof(double)分配它。

您可以通过使用malloc来避免在C ++中使用vector。如果要分配的确切大小,请使用new double[...]。无论哪种情况,您最终都会得到更具可读性的代码:

double **A = new double*[fullsize];
for (int i = 0 ; i != fullsize ; i++) {
    A[i] = new double[fullsize];
}
double *data = new double[fullsize*fullsize];

关于c++ - 在C++中将大型2D数组转换为1D数组的内存分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45459649/

10-11 04:12