如何在 c++ 中传递结构的动态数组?

How to pass Dynamic array of structures in c++?

本文关键字:结构 动态 数组 c++      更新时间:2023-10-16

我已经动态创建了一个结构数组,现在我愿意将其传递给函数。正确的方法是什么?我应该在 MAIN 中输入什么函数参数来执行此操作?

void function(Data *family)
{
//code
}
int main()
{
struct Data{
string name;
int age;
string dob;
};
Data *family = new Data[3];
function(Data);    //ERROR in parameter i guess!
}

最好使用 std::vector 或 std::shared_ptr使用更安全的方法。因为使用原始指针时很容易出错。 如果你真的需要使用原始指针,而不是你需要修复你的代码:

#include <string>
#include <iostream>
// "Data" should be declared before declaration of "function" where "Data" is used as parameter
struct Data {
std::string name;
int age;
std::string dob;
};
void function(Data *family)
{
std::cout << "function calledn";
}
int main()
{
Data *family = new Data[3];
// fill all variables of array by valid data
function(family); // Pass variable "family" but not a type "Data"
delete[] family; // DON'T FORGET TO FREE RESOURCES
return 0; // Return a code to operating system according to program state
}

每个c++程序员都需要学习std::vector,这是一个动态数组:

#include <vector>
struct Data{
string name;
int age;
string dob;
};
void function(const std::vector<Data>& family)
{
//code
}
int main()
{
auto family = std::vector<Data>(3);//family now contains 3 default constructed Data
function(family);
}
Not sure what actually what actually you are looking for, I guess you can try like this:
First define your structure outside from main so it would be accessible as function parameter. Then instead of Data pass object family to the function.
struct Data {
string name;
int age;
string dob;
}; 
void function(Data *family)
{
//code
}
int main()
{
Data *family = new Data[3];
function(family); 
}