如何通过指针打印数组
How can I print an array via pointer
我们的老师给了这个代码,我们需要让这个代码运行起来。
如何打印数组中的值?
cout << wizardsCollection->birthYear;
是 returns 我给的但是 wizardsCollection->nameSurname returns 空值。
这是代码的其余部分:
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;
}
你这里有一个大问题。 wizardsCollection
在堆栈上创建。一旦函数 returns,堆栈内存就消失了。您的指针将指向空 space。为此,您需要使用 std::vector 来管理内存。
#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";
}
还有其他方法可以做到这一点,但这是模拟你所拥有的。
我们的老师给了这个代码,我们需要让这个代码运行起来。
如何打印数组中的值?
cout << wizardsCollection->birthYear;
是 returns 我给的但是 wizardsCollection->nameSurname returns 空值。
这是代码的其余部分:
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;
}
你这里有一个大问题。 wizardsCollection
在堆栈上创建。一旦函数 returns,堆栈内存就消失了。您的指针将指向空 space。为此,您需要使用 std::vector 来管理内存。
#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";
}
还有其他方法可以做到这一点,但这是模拟你所拥有的。