Search code examples
c++arrayspointersstructure

How can I print an array via pointer


Our teacher gave this code and we need to get this code operational.

How can I print the values inside of array?

cout << wizardsCollection->birthYear;

is returns what I gave but wizardsCollection->nameSurname returns empty value.

Here's the rest of the code:

struct Wizard {
    string nameSurname;
    int birthYear;
    string hairColour;
};

struct Wizard *createWizards() {
    Wizard wizardsCollection[3];

    for (int index = 0; index < *(&wizardsCollection + 1) - wizardsCollection; index = index + 1) {
        wizardsCollection[index].nameSurname = "Name and surname of " + index;
        wizardsCollection[index].birthYear = 0;
        wizardsCollection[index].hairColour = "Hair colour of " + index;
    }

    return wizardsCollection;
}

int main()
{
    Wizard *wizardsCollection = createWizards();
    cout << wizardsCollection->nameSurname;
}

Solution

  • You have a huge problem here. wizardsCollection is created on the stack. As soon as the function returns, that stack memory goes away. Your pointer will be pointing into empty space. You need to use a std::vector for this, to manage the memory.

    #include <iostream>
    #include <string>
    #include <vector>
    
    struct Wizard {
        std::string nameSurname;
        int birthYear;
        std::string hairColour;
    };
    
    void createWizards(std::vector<Wizard> & wizardsCollection) {
        wizardsCollection.clear();
        for (int index = 0; index < 3; index++ ) {
            wizardsCollection.push_back(Wizard({
                "Name and surname of " + std::to_string(index),
                0,
                "Hair colour of " + std::to_string(index)
            }));
        }
    }
    
    int main()
    {
        std::vector<Wizard> wizardsCollection;
        createWizards(wizardsCollection);
        std::cout << wizardsCollection[0].nameSurname << "\n";
    }
    

    There are other ways to do it, but this models what you had.