Question

I have a function in c++ that needs a structure to work, but I have a hard time passing it. The structure looks like this:

struct RecAbbo{
    char name[20];
    char surname[20];
    int games;
    int won;
    int same;
    int lost;
    int place;
    int money;
}Abbo[100];

First I tried this:

void function(structure_name);

That did not work so I searched the internet. I found that you should do it like this:

void function(structure_name struct);

But it didn't work.

How do I do it?

Was it helpful?

Solution 2

First of all, I think you should use std::string for both name and surname, and also use std::array for the Abbo array:

struct RecAbbo {
    std::string name;
    std::string surname;
    int games;
    int won;
    int same;
    int lost;
    int place;
    int money;
};
std::array<RecAbbo, 100> Abbo;

you can declare a function func that accepts a RecAbbo by reference or by const reference:

void func(RecAbbo&);
void func(RecAbbo const&);

The latter is recommended if you are not planning on modifying the struct.

If you want to pass the array, you can use:

void func(std::array<RecAbbo, 100>&);
void func(std::array<RecAbbo, 100> const&);

or generalize it with iterators:

template<class It>
void func(It begin, It end);

or with templates:

template<std::size_t Size>
void func(std::array<RecAbbo, Size>&);

template<std::size_t Size>
void func(std::array<RecAbbo, Size> const&);

OTHER TIPS

It should be other way around

void function(struct RecAbbo structure_name)

Also, make sure your struct is defined before the prototype of the function function as the prototype uses it.

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

void function(RecAbbo structure_name)

Use

void function(RecAbbo any_name_for_object);

This will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top