3

I am creating a function for reading numbers from file into an array. But it seems like after returning from the function, the last value is lost. Here is my code:

void loadDataset(int* dataSet, int DataSetSize, char *filename) {
    FILE *fp;
    fp = fopen( filename , "r" );

    for(int i=0; i< DataSetSize; i++){
        fscanf(fp, "%d", &dataSet[sizeof(int) * i]);
    }

    for (int i = 0; i < DataSetSize; i++) {
        printf("%d\n", dataSet[sizeof(int) * i]);
    }

    fclose(fp);
}

int main(int argc, char *argv[]) {
    ...
    int* ds = malloc(sizeof(int) * DataSetSize);
    loadDataset(ds, DataSetSize, DatasetFilename);

    for (int i = 0; i < DataSetSize; i++) {
        printf("%d\n", ds[sizeof(int) * i]);
    }
    ...
}

The file I am testing with contains numbers from 1 to 6. While in function loadDataset, the printed result is

1
2
3
4
5
6

But when back in main function, the printed result is

1
2
3
4
5
0

What could be the problem?
I am sorry if it is something trivial I am missing, but I am not very familiar with programming in C.

1
  • Are you sure that the printed results are those?, it seems that you are skipping 4 numbers (if sizeof(int) == 4) on each iteration Commented Sep 30, 2019 at 14:19

1 Answer 1

5

This expression

fscanf(fp, "%d", &dataSet[sizeof(int) * i]);
                          ^^^^^^^^^^^^^^^      

does not make sense. As a result of using such an expression the program has undefined behavior because there are attempts to access memory outside the allocated array.

Use instead

fscanf(fp, "%d", &dataSet[i]);

or

fscanf(fp, "%d", dataSet + i);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Changing to fscanf(fp, "%d", &dataSet[i]); solved my problem. I will accept your answer in 5 minutes, because SO doesn't let me do it faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.