I want my code to read matrix.dat and store the numbers in a 4x4 matrix using pointers. Then I would like to print the matrix line by line. Although my program compiles, I get a core dump error before it prints its result.
This is my code:
Code:
#include <stdio.h>
#include <math.h>
/* function prototypes */
void prob1(void);
void prob2(void);
void gauss(int n, double **k, double *rhs);
/* add here additional function prototypes as needed */
main()
{
int menu;
printf("Enter the function number to execute (1-2):");
scanf("%d", &menu);
switch(menu){
case 1:
prob1();
break;
case 2:
prob2();
break;
default:
printf("prob%d() does not exist.\n", menu);
}
exit(0);
}
void prob2(void)
{
FILE *Inf_1;
double **A, *b;
int row;
char text[81];
int k=0,t=0;
b = (double *)malloc((size_t)3);
A = (double **)calloc(16, sizeof(double *));
Inf_1 = fopen("matrix.dat", "r");
printf(" Put your solution for problem 2 here:\n");
//By using a pointer to pointer **A and the function calloc()
//allocate the memory for the 4x4 matrix A[][]
//By using a pointer *b and the function malloc() allocate the memory
//for the 4-dimensional vector b[]
if(b==NULL)
{
printf("(main) malloc failed in double *b\n");
exit(1);
}
if(A==NULL)
{
printf("(main) calloc failed in double **a\n");
exit(2);
}
//Read the components of A and b from the given input file matrix.dat.
//The last line of the input file contains the components of b. The rows of
//matrix A are the first four lines of the input file.
if ((Inf_1 == NULL))
{
printf("Error opening the file\n");
exit(1);
}
while(fgets(text,81,Inf_1)!=NULL)
{
if (k < 5) {
sscanf(text, "%lf %lf %lf %lf", *A[t], *(A[t]+1), *(A[t]+2), *(A[t]+3));
k++;
t++;
}
else
sscanf(text, "%lf %lf %lf %lf", *b, *(b+1), *(b+2), *(b+3));
}
//Print the components of A[][] row by row, and the components of b[].
printf("\na[1][]= %lf %lf %lf %lf\n", *A[0],*(A[0]+1),*(A[0]+2),*(A[0]+3));
printf("a[2][]= %lf %lf %lf %lf\n", *(A[1]),*(A[1]+1),*(A[1]+2),*(A[1]+3));
printf("a[3][]= %lf %lf %lf %lf\n", *(A[2]),*(A[2]+1),*(A[2]+2),*(A[2]+3));
printf("a[4][]= %lf %lf %lf %lf\n", *(A[3]),*(A[3]+1),*(A[3]+2),*(A[3]+3));
}
When I explicitly store the matrix data as arrays (ie &A[0][0], &A[0][1]...), I receive a result. Why am I getting core dumps with pointers?
This is matrix.dat:
Code:
-1.0 1.0 -4.0 -0.5
2.0 1.5 3.0 2.1
-3.1 0.7 -2.5 4.2
1.4 0.3 2.4 -1.9
0.0 1.2 -3.0 -0.5