Gabriel Gabriel - 8 months ago 40
C++ Question

Creating and accessing a dynamic array of class objects

I've been working on a project that deals with phone directories. My program reads data from a datasheet and creates an array of phones.

I have 2 classes : softphone and fleet.

Softphone contains all the values for a phone (private) and get/set and print functions to access them (public).

class softphone {

string name;
//All my other variables

softphone(const softphone &obj);
//Get functions
string get_name();
//Set functions
void set_name(string);
//Print functions
void print_name();

Fleet contains the array of phones and output operation function with

class fleet {

//Some variables and buffers

softphone* phone; ->This is the array containing all the phones


//Read file and create array functions

void print_fleet();
//More output functions


The fleet class has a pointer to softphone and I use it to dynamically create an array of phones. It creates the array by reading the directories from a file. ( I don't know how many phone before run time.)

it counts the number of lines in the file and then create and array large enough to hold all the data:

phone = new softphone[number_of_lines - 1]; //Line 1 is header

It reads from file, saves the data with the set functions, then I increment the pointer using

So far so good. Now if I want to access these phone and call for a member function.


The compiler gives me no error but the output is garbage (Infinite random characters on screen.) I get a std::bad_alloc at memory location exception.

for(int i = 0; i < (number_of_lines - 1); i++){

Now it works. This way I can access all the phones and print them out fine. All the data is there. But I have to increment/decrement the pointer and I can't work with an index number.

How can i use a index number with this ? And why do the computer go crazy when I use it but is fine when I increment ?

Thanks for the replies,

Answer Source

When you create the array, phone is pointing to the first element. After that, you start incrementing the pointer until you get to the end of the array. At that point, phone is no longer pointing to the beginning of the array. Then, you run your loop which goes back through the pointers until it gets back to the beginning and things start working again. I recommend that you stop using pointer arithmetic and just use indices. Then, you're assured that phone is always pointing to the beginning of the array. Or, you can assign a different variable and use that for your pointers to fill the array. Or, you can use a std::vector as @PaulMcKenzie suggested.