我知道指向指针的指针是另一个指针的地址。将文件的参数传递为file*(*stream(而不是file*stream背后的确切原因是什么?如果有人能向我解释为什么需要这样,这样我才能更好地理解为什么这样做,我将不胜感激。下面提供了示例代码。
int SCAN(FILE * ( * stream)) {
int totalsize = 0;
int ch = 0;
//count the number of lines in file
do {
ch = fgetc( * stream);
if (ch == 'n') {
totalsize++;
}
} while (ch != EOF);
return totalsize;
}
在这种情况下,这毫无意义。如果要修改此指针引用的对象,则必须使用它。
例如:
int SCAN(FILE ** stream) {
int totalsize = 0;
int ch = 0;
//count the number of lines in file
*stream = fopen("myfile", "rt");
do {
ch = fgetc( * stream);
if (ch == 'n') {
totalsize++;
}
} while (ch != EOF);
return totalsize;
}
将双指针文件作为函数参数传递有什么意义?
SCAN()
不需要它。int SCAN(FILE *)
会很好1
。。。为什么它需要这样,这样我才能更好地理解为什么它有效。。。
常见的用法不是由于SCAN()
的实现,而是为了在相关函数中保留通用的签名样式。
请考虑以下内容。其他人可以使用FILE *
的地址
int SCAN(FILE * ( * stream));
int OPEN(FILE * ( * stream), const char *name);
int CLOSE(FILE * ( * stream));
int THIS(FILE * ( * stream), int foo);
int THAT(FILE * ( * stream), int bar);
另一方面,对于原始编码器来说,这可能是一个深夜。
1我会使用更宽的返回类型,因为文件行可以超过INT_MAX
。