问题
I am trying to pass a file pointer array to a function (not sure about the terminology). Could anyone please explain the proper way to send 'in[2]'? Thank you.
#include<stdio.h>
#include<stdlib.h>
void openfiles (FILE **in[], FILE **out)
{
*in[0] = fopen("in0", "r");
*in[1] = fopen("in1", "r");
*out = fopen("out", "w");
}
void main()
{
FILE *in[2], *out;
openfiles (&in, &out);
fprintf(out, "Testing...");
exit(0);
}
回答1:
Try:
void openfiles (FILE *in[], FILE **out)
{
in[0] = fopen("in0", "r");
in[1] = fopen("in1", "r");
*out = fopen("out", "w");
}
And call it openfiles (in, &out);
. Also, "pointer array" is ambiguous. Perhaps call it "array of FILE pointers" ?
回答2:
You need pointer to array of FILE* type
, Do as I did in below function. Also add ()
parenthesis like (*in)
to overwrite precedence Because by default []
has higher precedence over *
operator. SEE: Operator Precedence
void openfiles (FILE* (*in)[2], FILE **out){
(*in)[0] = fopen("in0", "r");
(*in)[1] = fopen("in1", "r");
*out = fopen("out", "w");
}
My example over string can be useful to understand the concept:
#include<stdio.h>
void f(char* (*s)[2]){
printf("%s %s\n", (*s)[0],(*s)[1]);
}
int main(){
char* s[2];
s[0] = "g";
s[1] = "ab";
f(&s);
return 1;
}
output:
g ab
CodePad
For OP: also read Lundin's comments to my answer Quit helpful!
来源:https://stackoverflow.com/questions/15151803/pass-pointer-array-to-function