Here's my analysis.
Code:
int main(void)
{
int n;
float *a, *b, *x;
printf("\nEnter the size of the linear system: \n");
scanf("%d", &n);
a=malloc((n*n)*sizeof(float));
b=malloc((n)*sizeof(float));
x=malloc((n)*sizeof(float)); /* good so far ... */
a=get_matrix(n, n); /* what happens in here? */
show_matrix(n, n, a);
b=get_matrix(n, 1); /* here too? */
OK so, assuming that get_matrix() hasn't changed, we have:
Code:
float *get_matrix(int m, int n)
{
int i, j;
float *a, A[m][n]; /* A is a variable length array from C99 */
a=&A[0][0]; /* a doesn't point to the memory you allocated in main() anymore */
for (i=0; i<m; i++) {
for (j=0; j<n; j++) {
printf("\nEnter with the element a%d%d of the matrix:", i+1, j+1);
scanf("%f", a);
a++;
}
}
a=a-m*n; /* odd, but acceptable */
return a; /* the same undefined behavior from earlier */
}
Let's look at what happens to x.
Code:
float *mult_matrix(int n, float *p, float *q)
{
int i, j;
float X[n]; /* variable length array again */
float *x;
for(i=0; i<n; i++) {
X[i]=0;
}
for (i=0; i<n; i++) {
for(j=0; j<n; j++) {
X[i]=X[i]+(*p)*(*q);
p++;
q++;
}
q=q-n; /* odd, but acceptable. */
}
x=X; /* memory leak here, x doesn't point to what you malloced anymore. */
return x; /* the same undefined behavior from earlier */
}
You can't use malloc AND variable length arrays at the same time. It causes the mistakes I noted. Returning a pointer to an array on the stack will just lead to invalid pointers after the array falls out of scope. Trying to use malloc and variable length arrays at the same time will just cause memory leaks. You really need to pick one or the other. Once you fix what's wrong in these functions you should be able to call them as many times as you want to.
Finally, you might be asking why I think show_matrix is OK.
Code:
void show_matrix(int m, int n, float *p)
{
int i, j;
printf("\n");
for (i=0; i<m; i++) {
printf("\n");
for (j=0; j<n; j++) {
printf(" %f ", *p);
p++;
}
}
printf("\n");
}
It's all OK because you don't do any assignments to p. As long as p points to an array of integers, you will see them.
I realize this is confusing, but you probably lack a good lesson on what pointers do, so look here before you try to fix it again. See if it clears anything up for you. Binky Pointer Fun Video