I must write a program named "matrizdinamica.c" that creates an m x n matrix, where m and p are argv[1] and argv[2]. The matrix elements are of type long int and are computed according to the following rules:
- Row no. 1: each element is 1
- Column no.1: each element is 1
- The remaining elements: x[i][j]=x[i-1][j]+x[i][j-1]; If x[i][j] > 10^6, then x[i][j]=1.
Once the matrix is created, I must write it on the stdout in matrix format. It mus be one line per row that must end always with "\n". Use the format "%li\t" for each element, except for the elements in the last column, in which case "%li\n" must be used.
If the matrix couldn't be created due to memory issues, the program must show nothing and return the code 71. If there are no issues, return 0. Upon termination, all the memory must be freed before the program terminates.
If we suppose our program is called "matrizdinamica", the command "./matrizdinamica 4 5" would produce:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
The code must work for large values of m and p.
So far, when I execute the following comands in order I get the desired result.
y16m038@triqui1:~/clases_pps/entregas_2022-23/4al6$ !gcc
gcc -ansi -pedantic -Wall -Wextra -Werror matrizdinamica matrizdinamica.c
y16m038@triqui1:~/clases_pps/entregas_2022-23/4al6$ ./matrizdinamica 4 5
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
Here's my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int filas = strtol(argv[1], NULL, 10);
int columnas = strtol(argv[2], NULL, 10);
long int **x;
int i; /* Recorre filas*/
int j; /* Recorre columnas */
/*Reserva de Memoria*/
x = (long int **) malloc (filas*sizeof(long int*));
if(x==NULL){
printf("Error: outta memory");
exit(71);
}
for (i=0;i<filas;i++){
x[i] = (long int*)malloc(columnas*sizeof(long int));
if (x[i]==NULL) {
exit(71);
}
}
/* Damos Valores a la Matriz*/
for (i=0; i<filas; i++){
for (j=0; j<columnas; j++){
if(i==0) x[i][j]=1;
else if (j==0) x[i][j]=1;
else {
x[i][j]=x[i-1][j]+x[i][j-1];
if (x[i][j]>1000000) x[i][j]=1;
}
}
}
/* Dibujamos la Matriz en pantalla */
for (i=0; i<filas; i++){
/*printf("\n");*/
for (j=0; j<columnas; j++){
if (j==columnas-1){
printf("%li\n", x[i][j]);
}
else {
printf("%li\t", x[i][j]);
}
}
}
/* if (i < filas -1){
printf("\n");}
}*/
/*printf("\n");*/
for(i = 0; i < filas; i++){
free(x[i]);
}
/* free(x);*/
return 0;
}
Could you please help me figure out why the teacher's delivery system says there is a segmentation fault core dump error and also that the exit status is not correct.
Thank you in advance. I hope I made myself clear.
I've tried handling the possible errors when allocating memory and taken care of freeing those memory addresses when I'm done.
I'm expecting to get the assignment approved because it's doing what it's supposed to do, but I don't see where I could be wrong.