Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing structs to functions

Tags:

c++

struct

I am having trouble understanding how to pass in a struct (by reference) to a function so that the struct's member functions can be populated. So far I have written:

bool data(struct *sampleData) {  }  int main(int argc, char *argv[]) {        struct sampleData {              int N;         int M;         string sample_name;         string speaker;      };          data(sampleData);  } 

The error I get is:

C++ requires a type specifier for all declarations bool data(const &testStruct)

I have tried some examples explained here: Simple way to pass temporary struct by value in C++?

Hope someone can Help me.

like image 777
Phorce Avatar asked Mar 03 '13 02:03

Phorce


2 Answers

First, the signature of your data() function:

bool data(struct *sampleData) 

cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:

bool data(struct sampleData *samples) 

But in C++, you don't need to use struct at all actually. So this can simply become:

bool data(sampleData *samples) 

Second, the sampleData struct is not known to data() at that point. So you should declare it before that:

struct sampleData {     int N;     int M;     string sample_name;     string speaker; };  bool data(sampleData *samples) {     samples->N = 10;     samples->M = 20;     // etc. } 

And finally, you need to create a variable of type sampleData. For example, in your main() function:

int main(int argc, char *argv[]) {     sampleData samples;     data(&samples); } 

Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.

However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:

// Note that the argument is taken by reference (the "&" in front // of the argument name.) bool data(sampleData &samples) {     samples.N = 10;     samples.M = 20;     // etc. }  int main(int argc, char *argv[]) {     sampleData samples;      // No need to pass a pointer here, since data() takes the     // passed argument by reference.     data(samples); } 
like image 123
Nikos C. Avatar answered Oct 01 '22 00:10

Nikos C.


Passing structs to functions by reference: simply :)

#define maxn 1000  struct solotion {     int sol[maxn];     int arry_h[maxn];     int cat[maxn];     int scor[maxn];  };  void inser(solotion &come){     come.sol[0]=2; }  void initial(solotion &come){     for(int i=0;i<maxn;i++)         come.sol[i]=0; }  int main() {     solotion sol1;     inser(sol1);     solotion sol2;     initial(sol2); } 
like image 37
Hossein Jandaghi Avatar answered Sep 30 '22 23:09

Hossein Jandaghi