I have two codes:
Normal:
int* p[5];
for (int i=0;i<5;i++){
int s = rand()%25;
p[i]=&s;
}
动态:
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;
}
现在,如果我打印数组 p,先打印
p[i]
,然后再打印*p[i]
,我会得到如下结果: static dynamic
0x22ff04 7 0x22ff30 7
0x22ff04 7 0x22ff24 14
0x22ff04 7 0x22ffa6 2
0x22ff04 7 0x22ff89 8
0x22ff04 7 0x22ff13 21
为什么在普通声明中,所有元素都指向同一位置,而在动态声明中会创建多个对象?
这是为什么呢?
s = rand()%25;
然后又取一个临时变量的地址吗?o.O
总之:UB(未定义行为)。 - Bartek Banachewicz