#include <stdio.h>
#include <stdlib.h>
struct SomeStruct{
int id;
int* dynamicArray;
};
int main(){
struct SomeStruct test;
test.id = 5;
// allocate array
test.dynamicArray = malloc(sizeof(int)*100);
// save struct to a file
FILE* handle = fopen("data", "wb");
fwrite(&test, sizeof(test), 1, handle);
fclose(handle);
return 0;
}
After running this code the size of data file is 16 bytes.obviously an integer pointer has been written to the file instead of whole dynamicArray elements. How can I write such structure correctly in a file?
dynamicArray, and not the struct, which contains the pointer to the data of the array, and not the array itself.SomeStructwith that data in the format.structto have a membersize_t sizeso you know how much memory to allocate, and elements to read, when you reload the file later.