Search code examples
carraysstringfilefopen

Saving numbers from file to array in C


In my code I opened file (succesful) and I am trying to get the numbers to array, but it does not working (control output is bad). Compiler did not show me any error.

link on txt file: https://textuploader.com/1amip

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

FILE *fr_koty;

int **array = NULL;

int x = 1;              /* Pocet radku */
int y = 1;              /* Pocet sloupcu */

char line[1024];
char *assistant_line;

int number;             /* Promena pro cislo*/

char *tab;


if((fr_koty = fopen("koty.txt", "r")) == NULL) {

    printf("Soubor se nepodarilo otevrit!");
    return 0;

}

while(fgets(line, 1023, fr_koty) != NULL) {

    array = (int **) realloc(array, x * sizeof(int *));

    array[x] = NULL;

    assistant_line = line;

    while(sscanf(assistant_line, "%d", &number) == 1) {

        array[x] = (int *) realloc(array[x], y * sizeof(int));

        array[x][y] = number;
        printf("%d  ", array[x][y]);

        if((tab = strchr(assistant_line, '\t')) != NULL) {

            assistant_line = tab + 1;
            y++;

        }
        else {

            break;

        }

    }

    putchar('\n');

    x++;

}

}

Output of numbers is random. I think the reason is bad working with memory, but I can not see the problem.


Solution

  • You're initializing x and y to 1, which is ok for the realloc, but as C arrays are 0 based, you need to use x-1 and y-1 to access the array elements.

    Or you init them to 0 and use (x+1) and (y+1) in the realloc call. I would prefer this way.