Search code examples
arrayscmallocdynamic-memory-allocationreturn-type

2D Array malloc - only last Items are shown


I want to malloc a 2d array and put data from a file in it. But it only shows the last items of my file. What do I have to do?

The file has 600.000 numbers like "280.000" in it.

double read_data(char *filename)
{

FILE *myFile = open_file(filename, "r");

int anzahl_zeilen = 0;
char zeile[80];

while (!feof(myFile))
{
    fgets(zeile, 80, myFile);
    anzahl_zeilen++;
}

rewind(myFile);


int i;

int **myArray = (int**)malloc(anzahl_zeilen*sizeof(int*));

for (i = 0; i < anzahl_zeilen; i++)
{
    myArray[i] = (int*)malloc(4*sizeof(double)); 
}



for (i = 0; i < anzahl_zeilen; i++)
{
    fscanf(myFile, "%lf %lf %lf %lf", &myArray[i,0], &myArray[i,1], &myArray[i,2], &myArray[i,3]);
}

printf("%lf %lf %lf %lf\n", myArray[0,0], myArray[0,1], myArray[0,2], myArray[0,3]);
printf("%lf %lf %lf %lf\n", myArray[1,0], myArray[1,1], myArray[1,2], myArray[1,3]);
printf("%lf %lf %lf %lf\n", myArray[2,0], myArray[2,1], myArray[2,2], myArray[2,3]);
printf("%lf %lf %lf %lf\n", myArray[3,0], myArray[3,1], myArray[3,2], myArray[3,3]);




return;
}

Solution

  • This while loop

    while (!feof(myFile))
    {
        fgets(zeile, 80, myFile);
        anzahl_zeilen++;
    }
    

    should be rewritten like

    while ( fgets(zeile, 80, myFile))
    {
        anzahl_zeilen++;
    }
    

    Also such expressions like this

    &myArray[i,0]
    

    are equivalent to

    &myArray[0]
    

    because within the square brackets there is used an expression with the comma operator. It seems you mean

    &myArray[i][0] 
    

    Also the function has the return type double but returns nothing.

    If you you are trying to allocate arrays of elements of the type double then in this case you need to write

    double **myArray = (double**)malloc(anzahl_zeilen*sizeof(double*));
    
    for (i = 0; i < anzahl_zeilen; i++)
    {
        myArray[i] = (double*)malloc(4*sizeof(double)); 
    }
    

    And the function must have the return type double ** and return the pointer myArray.