bobby
bobby

Reputation: 5

printf isn't printing the right number

I have this as my struct

    struct theFile{
        int count;
        FILE *fPointer;
        int *fileItems[];
    }myFile;

This is my method that saves the file in fileItems. It is saving the numbers properly. For example fileItems[0] = 5, fileItems[1] = 45, fileItems[2] = 35

    void saveFile(){
        myFile.fPointer = fopen("mileage.txt", "r");
        int i = 0;

        while (!feof(myFile.fPointer)){
            myFile.fileItems[i] = (int*)malloc(sizeof(int));
            fscanf(myFile.fPointer, " %d,", myFile.fileItems[i]);
            i++;
        }
        myFile.count = i;
    }

but when I go to print the contents of the file with this method it will print the first number properly but then it will print the rest as large numbers. Can someone please tell me why it isn't printing the correct content of the array.

    void viewFile(){
        for(int i = 0; i < myFile.count; i++){
            printf("%d, ", myFile.fileItems[i]);
        }
    }

also note, it is being written in c.

Upvotes: 0

Views: 148

Answers (3)

ElderBug
ElderBug

Reputation: 6145

fscanf ask for a pointer as argument, but it usually is the address of an existing int, not a 'real' int*. You probably meant to write :

struct theFile{
    int count;
    FILE *fPointer;
    int fileItems[N]; // You need to put a value as N, like 10, or else the array will be of size 0
}myFile;

Then

fscanf(myFile.fPointer, " %d,", &myFile.fileItems[i]); // with a & to get the address

This way you don't need a malloc and free. The rest is fine after that.

Edit: If you don't know how many int you will have beforehand, user694733's answer is better.

Upvotes: 1

user694733
user694733

Reputation: 16043

int *fileItems[]; is equal to int ** fileItems; Most likely you want a array of integers, and not array of pointers to integers.

Change struct declaration to int * fileItems;, and allocate list once before loop:

myFile.fileItems = malloc(sizeof(int) * initialNumberOfElements);

Later, if initialNumberOfElements was too small, then in realloc more space:

myFile.fileItems = realloc(myFile.fileItems, sizeof(int) * biggerElementCount);

Then argument to fscanf must be &myFile.fileItems[i].

Don't forget add error handling code for cases when allocation function fails. Same goes for any file functions you use: all I/O can fail.

Upvotes: 2

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

Make your declaration in the structure.

struct theFile{
    int count;
    FILE *fPointer;
    int *fileItems[MAX];// MAX=10;
}myFile;

Empty array subscript cannot know how arrays to point.

Upvotes: 0

Related Questions