How to grow 2d dynamically allocated string array in C++11 ?

101 views Asked by At

So, I have been doing this question : Q. Write a program that lets users keep track of the last time they talked to each of their friends. Users should be able to add new friends (as many as they want!) and store the number of days ago that they last talked to each friend. Let users update this value as well.

I have created pointer to pointer user_friends to store the 2D string array for names of friends and no. of days since last talked. It's a 3x2 array initially for 3 friends. The 2 columns store friend's name and no. of days ( both in string type pointer array ).

My main has this :

int tsize = 3;
string **user_friends = new string*[tsize];

for ( int i = 0; i < tsize; i++ )
{
    user_friends[i] = new string[2];
}

Here is the addFriends function to add friends in array.

 void addFriends( string **user_f , int tsize )
{
static int next_friend = 0;
int index = 0;
string days;

if ( next_friend >= tsize )
    {
        cout << "\nGrowing array now...";
        user_f = growArray ( user_f, tsize );
    }

cout << "\n\nEnter index : ";
cin >> index;
cin.ignore();

cout << "\nEnter friend's name : ";
getline( cin, user_f[index][0] );

cout << "\nEnter days since last talked with this friend : ";
getline (cin, days);
user_f[index][1] = days;

next_friend++;

}

Then there is this growArray function to expand the memory allocated to string array :

 string **growArray ( string **ptr, int cur_size )
{
string **new_ptr = new string*[ cur_size*2 ];

for ( int i = 0; i < cur_size; ++i )
{
    new_ptr[i] = new string[2];
}

for( int i = 0; i < cur_size; ++i )
{
    new_ptr[i] = ptr[i];
}

for ( int i = 0; i < cur_size; ++i )
{
    for ( int j = 0; j < 2; ++j)
    {
        new_ptr[i][j] = ptr[i][j];
    }
}

for ( int i = 0; i < cur_size; ++i )
{
    delete ptr[i];
}

delete[] ptr;
return new_ptr;
}

Then this display function to print the array.

void displayFriends( string **user_f, int tsize )
{
for ( int i = 0; i < tsize; ++i )
{
    for( int j = 0; j < 2; ++j )
    {
        cout << user_f[i][j] << "\t";
    }
    cout << endl;
}

}

Now, when I have entered upto 3 friends details, the program runs fine. When I start to enter the details of friend 4 ( i.e. When I type in index as 3 ) the program crashes. Is there any problem with the growArray function ?

Also, is the display function alright ?

1

There are 1 answers

2
MrGreen On

In the growArray function the first for loop should iterate from 0 to 2 * cur_size instead of 0 to cur_size.

for(int i = 0; i< 2 * cur_size; i++)
    new_ptr[i] = new string[2]