I'm working with makefiles, when compiling the following code, the random option works perfectly, but in the option to enter the matrix using the keyboard, this Segmentation fault (core dumped)
comes out, could you tell me why this is wrong or what is wrong in the code? , please.
The error originates after entering the matrix ( user(b, N, P);
). I think the error is in the printm(b, N, P);
function.
function.h
#ifndef function_H
#define function_H
int user(int **m, int N, int P);
void printm(int **m, int N, int P);
int generator(int **m, int N, int P);
void lmax(int **m, int N, int P);
#endif
function.cc
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "function.h"
using namespace std;
int user(int **m, int N, int P)
{
for (int i=0; i<N; i++)
{
for (int j=0; j<P; j++)
{
cin >> m[i][j];
}
}
return 0;
}
void printm(int **m, int N, int P)
{
int i;
for (i=0; i<N; i++);
{
for (int j=0; j<P; j++)
{
cout << " " << m[i][j] << " ";
}
cout << endl;
}
}
int generator(int **m, int N, int P)
{
srand(time(NULL));
for (int i=0; i<N; i++)
{
for (int j=0; j<P; j++)
{
m[i][j] = rand()%50-0;
cout << " " << m[i][j] << "\t";
}
cout << endl;
}
cout << endl;
return 0;
}
void lmax(int **m, int N, int P)
{
int j_max;
for (int i=0; i<N; i++)
{
j_max = 0;
for (int j=1; j<P; j++)
if (m[i][j_max] < m[i][j])
{
j_max = j;
}
m[i][j_max] = 0;
}
for (int i=0; i<N; i++) {
for (int j=0; j<P; j++) {
cout << " " << m[i][j] << "\t"; }
cout << endl; }
cout << endl;
bool kl = true;
for (int i=1; i<N; i++)
{
for (int j=0; j<i; j++)
{
if (m[i][j] != m[j][i])
kl = false;
}
}
if (kl)
{
cout << " Symetric matrix." << endl;
}
else
{
cout << " Not symetric matrix." << endl;
}
cout << endl;
}
test.cc
#include <stdio.h>
#include <iostream>
#include "function.h"
using namespace std;
int main()
{
int N, P, **a, **b;
char ch;
cout << "\n 1 - Initialize matrix by using a random number generator." << endl;
cout << " 2 - Initialize matrix via user input." << endl;
cout << " 0 - Exit." << endl;
cout << "\n Your choice: ";
do {
ch = getchar();
switch(ch)
{
case '1':
cout << "\n Rows: ";
cin >> N;
cout << " Columns: ";
cin >> P; cout << endl;
a = new int *[N];
for (int i=0; i<N; i++)
{
a[i] = new int [P];
}
generator(a, N, P);
lmax(a, N, P);
return 0;
case '2':
cout << "\n Rows: ";
cin >> N;
cout << " Columns: ";
cin >> P; cout << endl;
b = new int *[N];
for (int i=0; i<N; i++)
{
b[i] = new int [P];
}
user(b, N, P);
printm(b, N, P);
lmax(b, N, P);
return 0;
}
}
while(ch != '0');
return 0;
}