2

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);
FatSumo
  • 79
  • 7
  • 2
    "*I'm wondering, if it's a good idea to use & to point to the address of a normal variable*". Yes it's fine. What else would `&` be used for if not on a variable? – kaylum Aug 26 '21 at 20:35
  • I'm still starting in C, specially pointers. I was thinking maybe & (go to address) and * (show what's inside the address) was strictly reserved for pointers, and using in a normal variable could bug something out without me noticing. – FatSumo Aug 26 '21 at 20:50
  • 2
    The whole point of `&` is to get the address of a variable so you can put it into a pointer. – Barmar Aug 26 '21 at 20:54
  • 2
    I wouldn't think of the `&` as pointing to the address. `&foo` is the address of `foo`. If you want to think of an address as "pointing" at something, that's not too unreasonable, but `&` is just an operator that obtains the address. – William Pursell Aug 26 '21 at 20:58
  • Super this makes it much clearer, thanks a lot – FatSumo Aug 26 '21 at 21:45

1 Answers1

1

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();
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256