Passing an array of classes to a function

74 Views Asked by At

I'm having difficulty passing an array of class to an function which needs to operate on members of the classes, what I mean to do the code below should explain.

class Person {
  public:
    char szName[16];
};


void UpdatePeople(Person* list) //<- this is the problem.
{
    for (int i=0;i<10;i++)
    {
        sprintf(&list[i]->szName, "whatever");
    }
}

bool main()
{
    Person PeopleList[10];
    UpdatePeople(&PeopleList);

    return true;
}
1

There are 1 best solutions below

1
On BEST ANSWER

You do not need the & you can directly pass the array

UpdatePeople(PeopleList);

In this call PeopleList will decay into a Person*

Then in your UpdatePeople function you can use this as

for (int i=0;i<10;i++)
{
    sprintf(list[i].szName, "whatever");
}

I would, however, recommend using the C++ standard library

#include <iostream>
#include <string>
#include <vector>

class Person{
public:
    std::string szName;
};

void UpdatePeople(std::vector<Person>& people)
{
    for (auto& person : people)
    {
        std::cin >> person.szName;
    }
}

bool main()
{
    std::vector<Person> peopleList(10);
    UpdatePeople(peopleList);
    return true;
}