Reputation: 625
I have started to learn c++ and I am having a problem already.My program will take 4 arguments from the command-line. These arguments will be the dimensions of two multidimensional arrays.
./myprogram 2 2 2 2
This is how I enter the elements for the first 2x2 array:
1
2
3
4
Then I enter the elements for the second array:
5
Then I get an error in the terminal stating Segmentation fault (core dumped)
Here is the code that reads from the command line and tires to read in the array elements:
#include <iostream>
#include <stdlib.h>
using namespace std;
void readArr(int, int, double**);
int main(int argc, char* argv[]) {
int aRowCount = atoi(argv[1]);
int aColCount = atoi(argv[2]);
int bRowCount = atoi(argv[3]);
int bColCount = atoi(argv[4]);
std::cout << "Input accepted" << endl;
if(aColCount != bRowCount) {
std::cerr << "Col. Count of the first must match Row. Count of the second matrix." << endl;
return 1;
}
double **A = new double*[aRowCount];
for(int i = 0; i < aRowCount; i++){
A[i] = new double(aColCount);
}
std::cout << "allocating A" << endl;
double **B = new double*[bRowCount];
for(int j = 0; j < bRowCount; j++){
A[j] = new double(bColCount);
}
std::cout << "allocating B" << endl;
double **C = new double*[aRowCount];
for(int k = 0; k < aRowCount; k++) {
C[k] = new double(bColCount);
}
std::cout << "Reading in A" << endl;
readArr(aRowCount, aColCount, A);
std::cout << "Reading in B" << endl;
readArr(bRowCount, bColCount, B);
return 0;
}
void readArr(int rowCount, int colCount, double **array) {
for(int i = 0; i < rowCount; i++) {
for(int j = 0; j < colCount; j++) {
std::cin >> array[i][j];
}
}
}
Upvotes: 1
Views: 94
Reputation:
This:
A[i] = new double(aColCount);
should be:
A[i] = new double[aColCount];
and similar elsewhere. Your code allocates a single double, and initialises it with the value of aColCount
.
Upvotes: 1