I have two codes:
Normal:
int* p[5];
for (int i=0;i<5;i++){
int s = rand()%25;
p[i]=&s;
}
Dynamic:
int* p[5];
for (int i=0;i<5;i++){
int* s = new int;
*s = rand()%25; //Edit: typo, I didn't want to make a random pointer
p[i]=s;
}
Now if I print the array p, p[i] first and then: *p[i] after it, I get:
static dynamic
0x22ff04 7 0x22ff30 7
0x22ff04 7 0x22ff24 14
0x22ff04 7 0x22ffa6 2
0x22ff04 7 0x22ff89 8
0x22ff04 7 0x22ff13 21
Now why exactly are all elements in p pointing at the same location for normal declaration while in dynamic declaration there are multiple objects created?
Why is this?
In the first case, all entries point to s and are left dangling the moment s goes out of scope. Dereferencing p[i] leads to undefined behaviour.
In the second case, each entry points to a separate heap-allocated object. Here, there's no undefined behaviour (but there's a memory leak).
I have the sneaking suspicion you wanted an array of random values:
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::srand(time(0)); // Don't forget to seed!
std::vector<int> v(5);
std::generate(v.begin(), v.end(), random);
// or
std::vector<int> w;
std::generate_n(std::back_inserter(w), 5, random);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With