如何在 c++ 中传递结构的动态数组?
How to pass Dynamic array of structures in c++?
我已经动态创建了一个结构数组,现在我愿意将其传递给函数。正确的方法是什么?我应该在 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);
}
相关文章:
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 如何在C++中为堆栈动态创建结构?
- C++具有动态分配的字符数组的结构
- 如何为结构字段动态分配字符空间
- 使用列表进行动态结构分配
- 第一次尝试使用new动态创建结构数组,程序挂起没有错误
- 指向动态内存中结构中的变量时出现问题
- 具有字符串成员的结构的动态数组
- 如何在 c++ 中传递结构的动态数组?
- 指向结构中的数组的指针,其中每个字段都是一个动态数组
- OpenCL 中结构数组中的动态数组
- 结构内动态分配的数组
- 如何在构造函数中初始化结构体的动态数组?
- 使用C++动态分配结构的多维数组
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- C++类内部结构动态分配的方法
- 为结构动态分配内存
- MPI_Send+结构+动态内存分配
- C++ 用户输入的结构动态数组
- 结构继承层次结构-动态下转换