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.
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); }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With