Why is my program giving me segmentation fault?
My program is to find the values of variables using matrices and in matrices using GAUSS ELIMINATION method. It gives segmentation fault then I input the values of coefficients of the variables.
#include<stdio.h> void main() { int n; int i,j,l; float m; printf ("Enter the no. of variables: "); scanf ("%d", &n); j=n; float a[n][n+1], k[j]; printf ("Enter the co-efficients of the variables: "); for (i=0;i<n;i++) for (j=0;j<=n;j++) scanf ("%f", &a[i][j]); for (i=0;i<n;i++) { for (j=0;j<=n;j++) if (i==j) m=a[i][j]; for (j=0;j<=n;j++) a[i][j]=a[i][j]/m; for (j=0;j<=n;j++) k[j]=a[i][j]; for (i=1;i<n;i++) for (j=0;j<=n;j++) a[i][j]=a[i][j]-(a[i][j]*k[j]); } for (i=(n-1);i>=0;i++) { for (j=0;j<=n;j++) k[j]=a[i][j]; for (l=(n-2);l>=0;l--) for (j=0;j<=n;j++) { if (l>=i) continue; a[l][j]=a[l][j]-(a[l][j]*k[j]); } } for (i=0;i<n;i++) for (j=0;j<=n;j++) if (i==j) printf ("The value of %dth variable is %f", (i+1), a[i][j]); } |
you cannot do this "float a[n][n+1], k[j];"... that is declare a variable using a variable size..
try this "float a[50][50], etc.." .. use constant size for arrays.. if you want dynamic allocation use "malloc" . |
It's a good idea to use [CODE] tags to lay out your code nicely when posting to LQs, and also to use a comment to indicate where in your programme the error occurs :)
As imagine_me2 said, using malloc is a good idea: Code:
#include <stdlib.h> |
Quote:
Quote:
What did you intend for that to do? I don't think it causes a seg fault, but I don't think it does what you intended. It certainly does the wrong thing for Gaussian elimination. Quote:
Quote:
Quote:
Quote:
It is a good idea to either use a debugger or add some printfs to the code so you would know where the seg fault was and you wouldn't need to ask for help. Quote:
BTW: Code:
for (j=0;j<=n;j++) Also, are you sure you have a matrix in which it is safe to assume a[i][j] would never be zero at that point? |
@John My bad.. sorry overlooked it.
@Ahmad Why dont u run the binary through gdb and see where u get a SIGSEGV and post the result. We will then be sure. |
Quote:
In case you missed my answer earlier to where the SIGSEGV is, I'll explain it more clearly: Code:
for (i=(n-1);i>=0;i++) |
All times are GMT -5. The time now is 12:45 AM. |