Hello everyone.
I'm trying to create a program that solves a linear equation system in C.
To do that, initially,I created a structure named MATRIX. This structure has the pointer
to the line pointer vectors and the dimensions.
There is not syntax error, or compilation error. However, the Windows shows a message:
"Matrices.exe has stopped working."
Below, I created functions to allocate, enter with data and print the matrix:
(Compiled by MinGW in Code::Blocks)
Rodrigo
I'm trying to create a program that solves a linear equation system in C.
To do that, initially,I created a structure named MATRIX. This structure has the pointer
to the line pointer vectors and the dimensions.
There is not syntax error, or compilation error. However, the Windows shows a message:
"Matrices.exe has stopped working."
Below, I created functions to allocate, enter with data and print the matrix:
(Compiled by MinGW in Code::Blocks)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct MATRIX
{
int lines, columns; // The number of lines and columns respectively, obviously
int **element; // The pointer to the matrix, in fact
} MATRIX;
MATRIX *createMatrix(int nlines, int ncolumns) // Allocates the memory to a matrix and returns its address
{
MATRIX matrix; // The created matrix
int i;
matrix.lines = nlines; matrix.columns = ncolumns; // Saving the dimensions
matrix.element = (int**) malloc(nlines * sizeof(int*)); // Allocating memory to the vector of pointers of each line
if(matrix.element == NULL) // Check the memory allocation
{
printf("Memory Allocation Failed.\n");
exit(0);
}
for(i = 0; i < nlines; i++)
{
matrix.element[i] = (int*) malloc(ncolumns * sizeof(int)); // Allocate memory to each line
if(matrix.element[i] == NULL) // Check the memory allocation
{
printf("Memory Allocation Failed\n");
exit(0);
}
}
return &matrix;
}
void enterMatrix(MATRIX *matrix)
{
int i, j;
for(i = 0; i < matrix->lines; i++) // Passing through the lines
{
for(j = 0; j < matrix->columns; j++) // and through the columns
{
printf("a[%d][%d] = ", i, j);
scanf("%d", &(matrix->element[i][j])); // Saving each element value from user
}
}
}
void printMatrix(MATRIX *matrix)
{
int i, j;
for(i = 0; i < matrix->lines; i++) // Passing through the lines
{
for(j = 0; j < matrix->columns; j++) // and through the columns
printf(" %d",matrix->element[i][j]); // and printing each element
printf("\n"); // At the final of each line, break line
}
}
int main()
{
MATRIX *M = createMatrix(3, 3); // Create 3 by 3 matrix
enterMatrix(M); // Enter with data to matrix
printf("\n\n");
printMatrix(M); // Print the matrix
getch();
return 0;
}
Rodrigo