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


i have 2 codes:
normal:

int* p[5]; (int i=0;i<5;i++){     int s = rand()%25;     p[i]=&s; } 

dynamic:

int* p[5]; (int i=0;i<5;i++){     int* s = new int;     *s = rand()%25; //edit: typo, didn't want make random pointer     p[i]=s; } 

now if print array p, p[i] first , then: *p[i] after it, 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 elements in p pointing @ same location normal declaration while in dynamic declaration there multiple objects created?
why this?

in first case, entries point s , left dangling moment s goes out of scope. dereferencing p[i] leads undefined behaviour.

in second case, each entry points separate heap-allocated object. here, there's no undefined behaviour (but there's memory leak).


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -