Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ what is the difference between static and dynamic declaration internally

Tags:

c++

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?

like image 736
SmRndGuy Avatar asked Mar 28 '26 11:03

SmRndGuy


2 Answers

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).

like image 143
NPE Avatar answered Mar 29 '26 23:03

NPE


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);
}
like image 27
sehe Avatar answered Mar 30 '26 00:03

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!