简体   繁体   中英

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

I have created an array dynamically of structures and now i am willing to pass it to function.What is the correct method of doing it?What should i put in parameter of function in MAIN for doing it?

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!
}

It is better to use more safe ways using std::vector or std::shared_ptr . Because it is easy to make a mistake when you use raw pointers. If you really need to use raw pointer than you need fix your code:

#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 called\n";
}

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
}

Every c++ programmer needs to learn std::vector , which is a dynamic array:

#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); 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM