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.
Also here you declare an array with 12 elements (MAX). static Fruits type [MAX]
However you only fill it with 10 elements which means it can go from 0-9. If the random number int index = rand () % 11; ever picks 10 it will be out of bounds on the array and crash.
¿what do you think that type[10] and type[11] hold?
¿what will happen if you intend to do strcpy(s[K], type[10]) ?
> 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.
`delete' is not `bzero()'.
Oh my goodness! What a careless mistake! Thank you so much for pointing it out to me, it doesn't crash now!
Just another question though,
How can I confirm if the array has indeed been deleted?
I did a loop on the main function and tried like 15 times of it and didn't crash. Is that an indication that the delete operator is working? Since if i'm not wrong, too much of memory leak will lead to overflow and crashes?
> However you only fill it with 10 elements which means it can go from 0-9.
> If the random number int index = rand () % 11; ever picks 10 it will be out of bounds on the array and crash.
As you said, the array holds 12 elements. So index=10 is not out of bounds.
The crash happens because type[10] is NULL, and it gets dereferenced in `strcpy()'
@OP: assume that the program does what you tell it to do.