Sherlock Homies - 5 months ago 29

C Question

I am given a list of 24 scientific numbers in 1 column as txt file (use %le format).

`#include <stdio.h>`

#include <stdlib.h>

void main()

{

int i;

int j;

/*matrix*/

double** mat=malloc(24*sizeof(double*));

for(i=0;i<24;++i)

mat[i]=malloc(1*sizeof(double));

FILE *file;

file=fopen("input.txt", "r");

if ((file = fopen("input.txt", "r")) == NULL)

{

printf("Error! opening file");

// Program exits if file pointer returns NULL.

exit(1);

}

else

for(i = 0; i < 24; i++)

{

for(j = 0; j < 1; j++)

{

if (!fscanf(file, "%le", &mat[i][j]))

break;

printf("%le\n",mat[i][j]);

}

}

fclose(file);

}

Now i want to put this 1d array of 24 elements into a 4 by 6 matrix A.

how do i do that?

i have tried doing=>

`for(m=1;m<=4;m++)`

{

for(n=1;n<=6;n++)

{

mat[k][1]=A[i][j];

k++;

}

}

printf("%lf \n",A[i][j]);

But this does nothing.I am new to C so any help would be greatly appreciated thank you.

The program is too long for a simple task like read and write in a matrix i know..

Answer

```
for(m=1;m<=4;m++)
{
for(n=1;n<=6;n++)
{
mat[k][1]=A[i][j];
k++;
}
}
```

Your loop indices are `m`

and `n`

, but you're using `i`

and `j`

as your subscripts - `i`

and `j`

never get initialized or updated in the loop.

The bigger problem is that your are assigning the value of `A[i][j]`

to `mat[k][1]`

, rather than the other way around.

But this still has a problem - remember that in C, an N-element array is indexed from 0 to N-1. If `A`

is a 4x6 array and `mat`

is a 24x1 array (more on that later), then your loop should be written

```
for ( m = 0; m < 4; m++ )
{
for ( n = 0; n < 6; n++ )
{
A[m][n] = mat[k++][0];
}
}
```

The first element is at index 0, the second is at index 1, etc.

Regarding `mat`

...

It's not clear why you need to allocate `mat`

dynamically if you know it's going to store 24 values. It's also not clear why it needs to be a 24x1 array. Just declare it as a 24-element array of `double`

:

```
double mat[24];
...
for ( i = 0; i < 24; i++ )
{
if ( scanf( file, "%le", &mat[i] ) != 1 )
// handle read error
}
...
for ( k = 0, i = 0; i < 4; i++ )
for ( j = 0; j < 6; j++ )
A[i][j] = mat[k++];
```

Finally, `void main()`

should be `int main( void )`

.