Hi guys, I have this simple code below about pointers and dynamic 2D array.
The purpose of this program is to randomly generate a size and the size will be used to construct the height of dynamic 2D array (character array s)
The size is also used to run the loop to randomly populate the 2D array with values from another 2D character array.
Something is wrong with my code -
1) The delete operator doesn't seem to delete all the elements in array s. After the delete operator, I display values in array s and it shows that only the first element (s [0]) is deleted, but the rest displays the values. (s[1], s[2]...etc)
2) If I keep on running the program again and again, there will always be one time when it will crash and not even generate array s. Sometimes it's after 2 times, sometimes it's after 3-4 times.
Not sure what I'm doing wrong here! Please helpp!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAX = 12;
const int MAXSTR = 15;
typedef char* Fruits;
void populateSet (Fruits *, int);
int main ()
{
srand (time (NULL));
int size = rand () % 11;
Fruits *s;
s = new char * [size];
for (int i = 0; i < size; i++)
s[i] = new char [MAXSTR];
populateSet (s, size);
for (int i = 0; i < size; i++)
cout << s[i] << endl;
cout << "======================================================="
<< endl << endl;
//garbage collection
for (int i = 0; i < size; i++)
{
delete [] s [i];
cout << s[i] << " deleted" << endl;
}
delete [] s;
cout << *s << " deleted" << endl << endl;
}
void populateSet (Fruits *s, int size)
{
static Fruits type [MAX] = {"apple", "pear", "orange", "kiwi", "banana",
"honeydew", "papaya", "watermelon",
"durian", "mango"};
for (int i = 0; i < size; i++)
{
int index = rand () % 11;
strcpy (s [i], type [index]);
}
}
| |