Posted: Thu Nov 06, 2008 7:11 pm Post subject: malloc help - segmentation fault
I have to make a program that takes an input matrix (in a 2D array) and output it's inverse. The problem i have is allocating memory to the dynamic array. And yes, it must be a dynamic array and it must use malloc to allocate the memory. Please help, it's been KILLING me for the past couple days. It compiles, but when i run it i get a segmentation fault.
code:
int main (void)
{
int size, i;
printf ("Enter dimension of square matrix:");
scanf ("%d", &size);
double **entries = (double **)malloc(size*size*sizeof(double)); // HERE IS WHERE THE PROBLEM (probably) IS
printf ("\nEnter the %d entries of the matrix:", size*size);
for (i=0; i<size; i++)
{
int j;
for (j=0; j<size; j++)
{
scanf ("%lf", &entries [i][j]);
}
}
free (**entries);
return 0;
}
Thanks is advance.
Sponsor Sponsor
OneOffDriveByPoster
Posted: Thu Nov 06, 2008 8:19 pm Post subject: Re: malloc help - segmentation fault
shoobyman @ Thu Nov 06, 2008 7:11 pm wrote:
c:
double **entries = (double **)malloc(size*size*sizeof(double)); // HERE IS WHERE THE PROBLEM (probably) IS
Yes, your malloc did not do what you expected it to. You allocated a block of sizeXsize doubles and not size# of double* pointing to size# of doubles. You can access this like a one-dimensional array for example.
What are the requirements? Why do you have to use malloc? C has variable length arrays.