我已经动态分配了1D数组int * x和2D数组int ** y。我正在尝试显示由用户输入的长度确定的动态1D和2D数组的总和。我必须为1D数组的长度5和10运行两次程序,为2D数组的长度3,5和6,7运行程序。它崩溃了,并且未在控制台上显示任何金额。请帮忙!
#include <iostream>
using namespace std;
int main()
{
float sum = 0.0;
float sum2 =0.0;
float sum3 = 0.0; //1d array length 10
//1d array dynamic allocation
//2d array dynamic allocation
int length; //user length for 2d array, 5
int length2 = 3; //length for 2d array, 3
float oneArray; //length for 1d array
float oneArray2; // 1D array
int length1;
float sum4=0.0;
cout << "Enter dimensions " << endl;
cin >> length >> oneArray2;
cout << "Enter dimensions for 2d array " << endl;
cin >> length2 >> oneArray;
int *x = new int[oneArray2]; //single
int **y = new int* [length2]; //creates array
for(int i= 0; i < length; i++) //initializing 2d array
for(int j =0; j < length2; j++)
{
y[i][j] = i*j;
}
//initialize for 1d array
for(int l=0; l < oneArray2; l++)
{
x[l] = l;
}
for(int i= 0; i < length; i++) // allocating for 2d array
{
y[i] = new int[5];
}
for(int i=0; i< oneArray2; i++)
{
sum = sum + x[i];
cout << sum;
}
for(int k=0; k < length1; k++){
sum3 = sum3 + x[k];
cout << sum3;
}
for(int i= 0; i < length; i++) //initializing
for(int j =0; j < length2; j++)
{
sum2 = sum2 + y[i][j];
cout << sum2;
}
for(int i=0; i < 6; i++)
for(int j=0; j < 7; j++)
{
sum4 = sum4 + y[i][j];
cout << sum4;
}
for(int i=0; i < length; i++)
for(int j=0; j < length2; j++)
{
delete[] y[i][j]; //error message here too
}
for (int i=0; i < oneArray2; i++)
delete[] y[i];
return 0;
}
答案 0 :(得分:1)
首先,您要为2d数组分配内存,然后再初始化它
第二
为2D数组分配该内存的正确方法是
for(int i=0; i < length; i++)
//first you deallocate every row y[i]
delete [] y[i];
delete [] y;
以及一维数组
delete[] x;