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.
Passing structs to functions by reference: simply :)
First, the signature of your data() function:
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:
But in C++, you don't need to use
struct
at all actually. So this can simply become:Second, the
sampleData
struct is not known to data() at that point. So you should declare it before that:And finally, you need to create a variable of type
sampleData
. For example, in your main() function: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:
You need to tell the method which type of struct you are using. In this case, sampleData.
Note: In this case, you will need to define the struct prior to the method for it to be recognized.
Example:
Note 2: I'm a C guy. There may be a more c++ish way to do this.