Your code is fine (almost - see below). For structures, basically the same. Use
sizeof()
always, since the compiler might not generate the structure size you might think.
typedef struct xyz {
int a[5];
char b[7];
double c[2];
struct xyz *next;
char z;
} sxyz;
sxyz arr[8];
...
file.write(arr, sizeof(arr)); file.write(&arr[0], 8 * sizeof(sxyz));
Note I've done two things in two different ways:
1.
arr
in this context (as a pointer) means the same as
&arr[0]
- the address of the first element of the array. Both versions are correct in this regard.
2.
(No of structs) * (size of struct)
is not necessarily equal to
size of array of structs
As an exercise, try and work out in your head the size of
sxyz
above. Compare that with what your compiler says.
[optional advanced exercise]Find the compiler option that changes the size of
sxyz
without breaking your program. What does that do to the size of
arr
?
Cheers,
Peter