First off, This is a question about the compiler behavior not to correct the code either!
Here's my code but I cannot explain it to myself why I've got this results. I know it has a memory error (deleting pointer in other scope and before done with it) however the results only for the last element get problematic. Why the last element only has the raw generated rand
number?
#include <iostream>
using namespace std;
void populate(int *arrayToPopulate, int arraySize);
int main() {
int *ptr;
ptr = new int[100];
populate(ptr, 100);
for (int i = 0; i < 100; i++)
cout << ptr[i] << endl;
return 0;
}
void populate(int *arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] = rand() % 100 + 1;
}
delete [] arr;
}
The results:
8 50 74 59 31 73 45 79 24 10 41 66 93 43 88 4 28 30 41 13 4 70 10 58 61 34 100 79 17 36 98 27 13 68 11 34 80 50 80 22 68 73 94 37 86 46 29 92 95 58 2 54 9 45 69 91 25 97 31 4 23 67 50 25 2 54 78 9 29 34 99 82 36 14 66 15 64 37 26 70 16 95 30 2 18 96 6 5 52 99 89 24 6 83 53 67 17 38 39 2687021