Reputation: 1819
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?
Upvotes: 3
Views: 1823
Reputation: 14591
In first case, in each iteration you allocate an integer on stack and then assign this address to the array.
As there are no other variables on stack, s
is always allocated on the same address on stack, and you end up with all elements of p
pointing to the same address, which contains the last random value, i.e. 7. Besides that, after you exit the loop, you have no idea what can be written to this address as after leaving the scope of s
, compiler can use the same address to store some other data. You can prevent this by moving int s
outside of the loop, but still you would have all elements of p
pointing to the same stack address.
In second case, you allocate a new integer on heap in each iteration, so p
points to 5 different objects/addresses
what are you trying to achieve?
Upvotes: 1
Reputation: 393839
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);
}
Upvotes: 4
Reputation: 500903
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).
Upvotes: 6