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.
sizeof(int) == 4) on each iteration