Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration of a private array accessed by pointer in a class and memory allocation

I need some help with an in-class declaration of a pointer. I'm looking for a way to use a c-style array (so unfortunately no vectors) although I use c++. I can't manage to have no errors in execution such as "segmentation fault: 11" or "bus error: 10". The purpose is to have a way to contain 10 references to people in a class.

These pointers are declared in the .h file in this way:

private:
string * name;
string * surname;
int * index1;
int * index2;

and in the ctor in the .cc file I've used different ways to allocate memory, such as:

string * name = new string[10];
string * surname = new string[10];
int * index1 = new int[10];
int * index2 = new int[10];

but I got runtime errors, maybe because it actually doesn't access the private variables or it exceeds memory ("segmentation fault"). If I don't write the lines above, the output is "bus error" while executing. I don't get errors in compilation, only during the execution. I can't change the private variable types in .h file and it doesn't allow me to use new in the class as it would be an extension of C++11.

Any help would be very appreciated

like image 856
Lorenzo Avatar asked Oct 19 '25 01:10

Lorenzo


1 Answers

I think you should use std::vector, as there's very little reason for beginners to use new/delete.

In your case the private section could change to:

private:
std::vector<string> name;
std::vector<string> surname;
std::vector<int> index1;
std::vector<int> index2;

and in the constructor, could have this:

name.resize(10);
surname.resize(10);
index1.resize(10);
index2.resize(10);
like image 169
Martein Txz Avatar answered Oct 21 '25 15:10

Martein Txz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!