dace
dace

Reputation: 124

Losing array pointer value?

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.

Upvotes: 3

Views: 138

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

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);

Upvotes: 5

Related Questions