Reputation: 305
I have this class in a hpp file:
class info
{
public:
float lux[100];
float pwm[100];
float time[100];
float ref_lux;
int counter_samples_stream;
};
In the cpp file that contains this header, I create a vector of this class and because I put it in the beginning of the cpp file it is a global variable. This is the code I use to create it:
std::vector <info*> vect_node[3]; //creates 3 instances of class info in a vector
Inside the function(called abc) we are changing and initializing the vector's data by doing per example this: vect_node[1].lux[0] = 25;
.
We are also trying to access the vector's data in another function(called zys) but when trying to access it the program crashes and returns core dumped.
Neither function abc or zys pass the vect_node in its arguments. The doubt is how can I write in vec_node
in a function in a way it changes its values permanently(and not only in the function) and read from this vector now updated in another function(syz).
Upvotes: 0
Views: 96
Reputation: 4760
The syntax std::vector<info*> vect_node[3];
will create an array of 3 std::vector
s, in the same way that int my_array[3];
declares an array of 3 int
s.
If you want to create a single std::vector
with an initial capacity of 3, use the fill constructor. For example,
std::vector<info*> vect_node{3, nullptr};
will construct a std::vector
called vect_node
with an initial capacity of 3, where every element in the vector is of type info*
has the initial value nullptr
.
As pointed out in the comments, if you do not want a vector of pointers, you can instead use
std::vector<info> vect_node{3};
In this case, a std::vector
of size 3 will be created called vect_node
. Each element of the vector will contain an info
object. Using this approach, your
vect_node[1].lux[0] = 25;
will now be valid.
Documentation for the std::vector
constructors can be found here.
Upvotes: 2
Reputation: 460
One way to easily initialise your vector of pointers is to use smart pointers so in one line you can do:
std::vector<std::shared_ptr<info>> vect_node(3, std::make_shared<info>());
Which will create a vector of three smart pointers and allocate the memory. You will then be able to just discard the vector without much worrying. You can modify elements with vect_node[O]->lux[0] = 10;
You just need to create a constructor for your class info
.
Upvotes: 1