I have already dynamically allocated the 1D array, int *x, and the 2D array, int **y. I am trying to display the sum of the dynamic 1D and 2D arrays determined by the lengths the user inputs. I have to run the program twice for the length 5 and 10 for the 1D array, and lengths 3,5 and 6,7 for the 2D array. It is crashing and not displaying any sums on the console. Please help!
#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;
}
first you allocate memory for the 2d array before you initialize it not the other way around
Second
the correct way to deallocate that memory for a 2D array is
for(int i=0; i < length; i++)
//first you deallocate every row y[i]
delete [] y[i];
delete [] y;
and for the 1D array
delete[] x;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.