fread pointer in C

Viewed 127

I declared a non pointer variable to use as a buffer for my fread function in C. fread specifies that the buffer should be a pointer, I used the & sign to point at the address of my variable buffer (if my logic is correct). I'm wondering, if it's a good idea to use & to point to the address of a normal variable. I'm not sure if this practice could be a 'bad' thing / habit that I should avoid. thanks a lot.

int16_t buffer;

fwrite(&buffer, (size_t) sizeof(int16_t), (size_t) 1, output);
1 Answers

if it's a good idea to use & to point to the address of a normal variable.

Yes - a good idea and a common usage in C when the file is opened in binary mode.

Better to add error checking too, size to the object (not type) and remove unnecessary casts.

int16_t buffer;
...
size_t wcount = fwrite(&buffer, sizeof buffer, 1, output);
if (wcount != 1) Handle_Error();

Alternatively use an array.

#define N 42
int16_t buf[N];
... 
//  Here, array `buf` converts to the address of the first element.
//                     vvv
size_t wcount = fwrite(buf, sizeof buf[0], N, output);
if (wcount != N) Handle_Error();
Related