Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing array pointer value?

Tags:

arrays

c

pointers

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.

like image 623
dace Avatar asked Jan 23 '26 06:01

dace


1 Answers

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);
like image 138
Vlad from Moscow Avatar answered Jan 24 '26 21:01

Vlad from Moscow