1

I'm learning C at the moment and wrapping my head around pointers. I understand & can be used to retrieve the address of a var in memory. I'm curious to know why this particular call to read() is passing the address of the char var.

Of course, the intention here is to read the input from shell 1 by 1, but why is it necessary to provide the address of c? Or is it merely a preference? I guess I'm not clear on when using a pointer is necessary.

int main() {
  char c;
  while (read(STDIN_FILENO, &c, 1) == 1 && c != 'q');
  return 0;
}
0xgareth
  • 603
  • 1
  • 11
  • 30
  • 8
    When you want a function to *modify* the variable you have outside of it (`c`), you pass its address, so it can write to it. C has pass-by-value only parameter passing. – Eugene Sh. Jan 18 '21 at 16:15
  • Because [read(2)](https://man7.org/linux/man-pages/man2/read.2.html) is documented to be used this way – Basile Starynkevitch Jan 18 '21 at 16:53
  • You need to understand the difference btw parameters passed by value and by address (also called by reference). cf. this [post](https://stackoverflow.com/q/373419/14393739) for example... – Rachid K. Jan 18 '21 at 18:52

1 Answers1

2

why is it necessary to provide the address of c

read() needs an address to know where to store data. c is a char. To only pass c would pass the value of the char and not its address. Hence code passed the address of c.

Alternatively, form an array. Code read(array_name, ...) will automatically convert the array to the address of its first element.

char c;
read(STDIN_FILENO, &c, 1);

// or
char d[1];
read(STDIN_FILENO, d, 1);

// or 
#define N 42 /* or whatever */
char e[N];
read(STDIN_FILENO, e, sizeof e);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • makes sense, cheers! I guess this could be used different if the read function returned a value that you could place in a variable, rather than modifying in place – 0xgareth Jan 18 '21 at 16:58
  • @garethiv R With `read(...,1)`, sure returning a `char` is easy, but with `read(..., N)`, not readily possible in C to return an _array_. – chux - Reinstate Monica Jan 18 '21 at 17:02
  • @garethiv From the caller's perspective, `read(STDIN_FILENO, e, sizeof e);` acts like pass-by-reference for `e`. Yet from the `read()` point-of-view, it is still pass-by-value as it receives the address of `e` and `read()` needs to know the size of `e` via other means (`sizeof e`) – chux - Reinstate Monica Jan 18 '21 at 17:05