c++struct

Passing structs to functions


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.


Solution

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