c++arraysstructuremembers

Passing structures and structure members to functions


When passing structures to functions what would the prototype / header look like? What would they look like when passing members of structures to functions?

For example...

struct a_struct{
int a;
int b;
};

a_struct point;

void f1(a_struct)
void f2(a_struct)

And lets say that I want to pass the whole structure to f1, but just a member to f2. Would I use the data type a_struct as parameter for both? Or would f2 have a different data type because I am only passing the member which is an int. Would this vary for an array of structures? The program I have been tasked to write is supposed to use arrays of structures. I figured that this wouldn't make much of a difference except that it will be passed by reference automatically.


Solution

  • When passing objects around (not just scalar values), you have to be concerned about memory ownership and copying, etc. This means that you have multiple options for how you declare the interface for your function. For example, you can pass by reference or pass by value.

    A possible declaration for you might be:

    void f1(a_struct& my_struct);
    

    This would pass a reference to the a_struct object and prevent any copying of the object. However, your example structure just contains scalar values, so the possibility of copying the object isn't cause for too much worry. As a result, this would suffice:

    void f1(a_struct my_struct);
    

    As far as passing a member of the struct into a function, the function would need to be declared to take the type of the member. For example, to pass the a member of the a_struct into a function, you would do:

    void f1(int val);
    

    Finally, arrays do complicate things as they would come in as a pointer to the function. For example, to pass an array of a_struct objects, you would make this declaration:

    void f1(a_struct* my_struct);
    

    However, you could then simply reference the parameter normally. For example:

    my_structs[1];