A
axcytz
Hello all,
I have the following code to have a 2D array, and my aim is to have a matrix whose (1) column size is variable(i.e. 1st row has size 3, 2nd has 2, 3rdhas 5, and so on);(2) row size is dynamically changed (I want to be able to add new rows in the future.) Unfortunately, I can't achieve these goals. Thanks for your helps in advance!
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
int rowSize = 3, columnSize = 5, z=0, counter = 0;
int **array;
array = new int* [rowSize];
for (int i = 0; i < rowSize; i++)
array = new int [columnSize]; // rowSize* columnSize matrix iscreated
int* addedRow;
addedRow = new int [rowSize]; //to add new rows
for (int z = 0; z < counter; z++ ){ //z is the index of new row
array[rowSize+z] = new int [size[z]];} //to add new row
counter++; // count the added rows
cout << "added row's number of elements:\n";
cin >> addedRow[z];
for (int i = 0; i < addedRow[z]; i++ ){
array[z] = 1; //all elements are set to 1
}
for(int i=0; i<rowSize; i++)
{
for(int j=0; j<n; j++)
{
cout << array[j] << " ";
}
cout << endl;
}
for (int i = 0; i < rowSize; i++){
delete [] array;
}
delete [] array;
}
I have the following code to have a 2D array, and my aim is to have a matrix whose (1) column size is variable(i.e. 1st row has size 3, 2nd has 2, 3rdhas 5, and so on);(2) row size is dynamically changed (I want to be able to add new rows in the future.) Unfortunately, I can't achieve these goals. Thanks for your helps in advance!
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
int rowSize = 3, columnSize = 5, z=0, counter = 0;
int **array;
array = new int* [rowSize];
for (int i = 0; i < rowSize; i++)
array = new int [columnSize]; // rowSize* columnSize matrix iscreated
int* addedRow;
addedRow = new int [rowSize]; //to add new rows
for (int z = 0; z < counter; z++ ){ //z is the index of new row
array[rowSize+z] = new int [size[z]];} //to add new row
counter++; // count the added rows
cout << "added row's number of elements:\n";
cin >> addedRow[z];
for (int i = 0; i < addedRow[z]; i++ ){
array[z] = 1; //all elements are set to 1
}
for(int i=0; i<rowSize; i++)
{
for(int j=0; j<n; j++)
{
cout << array[j] << " ";
}
cout << endl;
}
for (int i = 0; i < rowSize; i++){
delete [] array;
}
delete [] array;
}