简体   繁体   中英

Why pass the address of char variable to standard read() function?

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;
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM