0

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 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

smacks forehead. thanks for that. solved my problem alright.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.