2

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

2 Answers 2

2

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" ?

Sign up to request clarification or add additional context in comments.

Comments

0

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!

6 Comments

Note however that in the special case of a function parameter, FILE* (*in)[2] is equivalent to FILE* in[2], both are array pointers to an array of 2 FILE*.
@Lundin I am bit unsure. Ok then In function parameter does char* (*s)[2] == char* s[2] ?
@Lundin I checked here And You are CORRECT. In function parameter does char* (*s)[2] == char* s[2].. Thanks :)
Function parameters are quite confusing. No matter if you type a formal array pointer declaration as you did, or if you type something that looks like an array declaration as I did, or if you merely type FILE*, it will all boil down to a pointer in the end.
Though please note that the version in your answer is correct, it is the most formal and stylistically correct way of declaring such a parameter. But it can be hard to read and understand for the average programmer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.