###### Calcifa97

2019-12-13 16:11 阅读 231

# 请问为什么用new建立动态二维数组就会报错，用malloc就不会报错。

``````void Matrix()
{
int i;
//double** P_ca_x = new double* [Times];
//double** P_ca_y = new double* [Times];
//double** P_ca_z = new double* [Times];
//double** v_ca_x = new double* [Times];
//double** v_ca_y = new double* [Times];
//double** v_ca_z = new double* [Times];
//double** v_ca = new double* [Times];
P_ca_x = (double**)malloc(sizeof(double*) * Times);
P_ca_y = (double**)malloc(sizeof(double*) * Times);
P_ca_z = (double**)malloc(sizeof(double*) * Times);
v_ca_x = (double**)malloc(sizeof(double*) * Times);
v_ca_y = (double**)malloc(sizeof(double*) * Times);
v_ca_z = (double**)malloc(sizeof(double*) * Times);
v_ca = (double**)malloc(sizeof(double*) * Times);
for (i = 0; i < Times; i++)
{
//P_ca_x[i] = new double[Num];
//P_ca_y[i] = new double[Num];
//P_ca_z[i] = new double[Num];
//v_ca_x[i] = new double[Num];
//v_ca_y[i] = new double[Num];
//v_ca_z[i] = new double[Num];
//v_ca[i] = new double[Num];
P_ca_x[i] = (double*)malloc(sizeof(double) * Num);
P_ca_y[i] = (double*)malloc(sizeof(double) * Num);
P_ca_z[i] = (double*)malloc(sizeof(double) * Num);
v_ca_x[i] = (double*)malloc(sizeof(double) * Num);
v_ca_y[i] = (double*)malloc(sizeof(double) * Num);
v_ca_z[i] = (double*)malloc(sizeof(double) * Num);
v_ca[i] = (double*)malloc(sizeof(double) * Num);
}
}
void Delete()
{
int i;
for (i = 0; i < Times; i++)
{
//delete[] P_ca_x[i];
//delete[] P_ca_y[i];
//delete[] P_ca_z[i];
//delete[] v_ca_x[i];
//delete[] v_ca_y[i];
//delete[] v_ca_z[i];
//delete[] v_ca[i];
free(P_ca_x[i]);
free(P_ca_y[i]);
free(P_ca_z[i]);
free(v_ca_x[i]);
free(v_ca_y[i]);
free(v_ca_z[i]);
free(v_ca[i]);
}
//delete[] P_ca_x;
//delete[] P_ca_y;
//delete[] P_ca_z;
//delete[] v_ca_x;
//delete[] v_ca_y;
//delete[] v_ca_z;
//delete[] v_ca;
free(P_ca_x);
free(P_ca_y);
free(P_ca_z);
free(v_ca_x);
free(v_ca_y);
free(v_ca_z);
free(v_ca);
}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

#### 2条回答默认 最新

• 已采纳
J4cks0n 2019-12-13 16:40

不会报错把，麻烦把错误信息贴一下。不应该报错的

你先把下面的程序编译一下，如果没报错就不是new的问题

``````#include <iostream>
#include <string.h>

using namespace std;

int main()
{
//申请
double ** a = new double*[5];
for(int i = 0; i<5; ++i)
{
a[i] = new double[6];
memset(a[i], 0, sizeof(double)*6);
}

//赋值
for(int i = 0; i<5; ++i)
for(int j = 0; j < 6; ++j)
a[i][j] = i*j*1.3;

//输出
for(int i = 0; i<5; ++i)
{
for(int j = 0; j < 6; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}

//删除
for(int i = 0; i<5; ++i)
{
delete[] a[i];
}
delete[] a;
}
``````
点赞 评论 复制链接分享
• 502203305 2019-12-13 16:42

类型不一致。new的数组是有长度的，而malloc指针是没有长度的。new后用对应类型保存，或者强转。

点赞 评论 复制链接分享