为什么通过引用传递只使用在这个 C 程序的参数列表中声明的指针?

Why passing by reference works using only pointers declared in the argument list of this C program?

这是来自 Robert Wood 的 "C Programming for Scientists and Engineers" 的程序 3.7。在下面的代码中,指针没有在 main() 函数体中声明和初始化,而是直接在 read_data() 函数的参数列表中声明和初始化。

一般写代码的时候,我先声明3个指针(int *int_ptr, float *float_ptr, char *char_ptr) 然后给a, b 和 c 给他们。但是在下面的程序中,调用 read_data(&a, &b, c) 时传递了 "address of" 操作符;通过 void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...} 的参数列表,我们有 "contents of"运营商,这似乎不一致,但有效。 此外,fscanf(stdin,"%d %f %s", int_ptr, float_ptr, char_ptr);将用户提供的数据存储在指针的地址中,而我认为它们应该像这样写在变量 a、b 和 c 的内容中:

fscanf(stdin,"%d %f %s", int_*ptr, *float_ptr, *char_ptr);

但我错了

否则程序可以运行,但如果我必须这样写,我将无法编写。所以,我希望你能帮助我理解并提供替代解决方案。

/* Program 3.7- Use of functions for input and output of data */
#include <stdio.h>

int main(void) {
  int a;
  float b;
  char c[11];

  /* function prototype */
  void read_data(int *, float *, char *);
  void write_data(int, float, char[]);

  /*call the function*/
  read_data(&a, &b, c);
  write_data(a, b, c);

  return (0);
}

/*Function: read_data - reads an int, float and char string*/
void read_data(int *int_ptr, float *float_ptr, char *char_ptr) {
  fprintf(stdout, " Supply an integer, a float and a string (max. 10 chars):");
  fscanf(stdin, "%d %f %s", int_ptr, float_ptr, char_ptr);
  return;
}

/* Function: write_data - displays an int, float and char string*/
void write_data(int i, float j, char k[]) {
  fprintf(stdout, " The supplied data is: %d %f %s\n", i, j, k);
  return;
}

这并不矛盾,您只是推断了函数的错误属性。

注意区别:

函数声明:

void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}

还有一个函数调用

read_data(int_ptr, float_ptr, char_ptr);

But in the program below, "address of" operators are passed when calling read_data(&a, &b, c); through the argument list of void read_data(int *int_ptr, float *float_ptr, char *char_ptr){...}, where we have "contents of" operators, which seems inconsistent, but works

你对这个函数的参数列表代表什么的推断是造成你困惑的原因。该函数不接受 "contents of" 指针,而是指针本身。由于 "address of" 运算符 returns 是一个指针,因此使用 read_data(&a, &b, c)

调用该函数完全没问题