0

I need to pass an array of structures defined in a file "file1.c" to a function, lets say "myFunc()", defined in another file "file2.c". The thing is that I don't know how to set the prototype of myFunc() in my header file "header.h" or in the function itself in my file2.c because the struct will only be defined in file1.c . Here is an example.

file1.c

#include "header.h"

#define dim 30
#define searchAgents 30

struct Wolf{

    double pos[dim];
    double fitness;

}Pack[searchAgents];

int main(){
    myFunc(Pack); //not sure it's ok
    return 0;
}

file2.c

#include "header.h"

void myFunc(struct Wolf Pack[]){ //I don't know how to set this argument
    Pack[0].pos[0] = 1; //just an example
}

header.h

#ifndef HEADER_H_
#define HEADER_H_   

void myFunc(struct Wolf); //I don't know how to set this prototype

#endif

I read about passing structures to functions but it's different when you have your function defined in another file. Thanks for your time.

4
  • What you did looks fine except that you should just say void myFunc(struct Wolf Pack[]); in header.h. Probably you want the searchAgents define in there as well so that you know how many wolves there are in myFunc(). (You are not passing a structure but a pointer to the first structure in the Pack array.) Commented Sep 23, 2014 at 16:31
  • It outputs this: error: array type has incomplete element type Commented Sep 23, 2014 at 16:38
  • 2
    You need to insert the struct in header.h. File2.c doesnt know about this struct Commented Sep 23, 2014 at 16:39
  • And the function call it's ok? Because it outputs this: error: type of formal parameter 1 is incomplete myFunc(Pack); Commented Sep 23, 2014 at 16:43

2 Answers 2

1

header.h

#ifndef HEADER_H_
#define HEADER_H_   

//Add all needed includes

#define dim 30
#define searchAgents 30

typedef struct Wolf{
    double pos[dim];
    double fitness;
}Pack; //Declaration

void myFunc(Pack *);

#endif

In main

#include "header.h"

int main(){
    Pack packArray[searchAgents]; //Definition or initialization if you like
    myFunc(packArray);
    return 0;
}

file2.c

#include "header.h"

void myFunc(Pack *pack){ //just a pointer to Pack structure
    pack[0].pos[0] = 1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try making Pack[] as an extern type variable

extern keyword tells the compiler that the variable is define in some other .c file which is compiled along with this file with -o option in gcc compiler .

ex

extern Pack[10]; 

Comments

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.