简体   繁体   中英

How to fill an array of structs using a pointer while reading from a file in C

the following has poped up while studying and I would like whether it does what it is supposed to. Let's say we have the following struct:

typedef struct a{
      int x;
      int y;
}a;

And we have a binary file where we can find info about multiple instances of the above struct, and we want to have an array of these structs and fill them one by one. Can we do the following?

a* aStruct= malloc(sizeof(a)*10); // aStruct[10]
a* temp;
int i = 0;
while(i < 10){
        temp = aStruct+i++;
        fread(&temp->x, sizeof(int), 1, inputFile);
        fread(&temp->y, sizeof(int), 1, inputFile);
}

Does the above means that in the end, the array aStruct will be filled with the contents from the file? If not, how can we do it?

Yes, that should work. But there's no need for the temp variable.

for (i = 0; i < 10; i++) {
    fread(&(aStruct[i].x), sizeof aStruct[i].x, 1, inputFile);
    fread(&(aStruct[i].y), sizeof aStruct[i].y, 1, inputFile);
}

It's generally more idiomatic and easier to read if you use array indexing notation when you're using a pointer as an array.

I used sizeof aStruct[i].x rather than sizeof(int) so that it will automatically pick up the type from the structure declaration, rather than requiring you to keep them in sync if the structure changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM