C++ 当同一个指针与另一个指针一起打印时,它会给出不同的地址吗? #包括 使用名称空间std; int main() { int a[]={10,20,30,40,50}; 整数*b,**c,*d; cout

C++ 当同一个指针与另一个指针一起打印时,它会给出不同的地址吗? #包括 使用名称空间std; int main() { int a[]={10,20,30,40,50}; 整数*b,**c,*d; cout,c++,pointers,C++,Pointers,如果您想要为两个输出获得相同的值,那么insert语句 Is cout<<a is equivalent to cout<<&a ? b = a; cout<<b; 在表达式中,数组被隐式转换为指向其第一个元素的指针。因此,在语句中,表达式a被转换为指向其第一个元素的指针,并被分配给b 在这份声明中 Is cout<<a is equivalent to cout<<&a ? b = a; cout

如果您想要为两个输出获得相同的值,那么insert语句

 Is cout<<a  is equivalent to  cout<<&a ?
b = a;
cout<<b;
在表达式中,数组被隐式转换为指向其第一个元素的指针。因此,在语句中,表达式a被转换为指向其第一个元素的指针,并被分配给b

在这份声明中

 Is cout<<a  is equivalent to  cout<<&a ?
b = a;
cout<<b;
b将指向数组a的第二个元素(索引为1)

编辑:哦,我理解你的问题。似乎当函数whrn中没有使用变量b时,编译器只是将其从生成的目标代码中删除。当使用变量b时,编译器会在堆栈上为其分配内存。因此,a的地址会根据是否使用变量b而改变

b = a+1
编译器可能正在优化b out。请尝试在编译器上将优化设置为“无”

Q1 : why different value printed for a in 2 cases
试试看,让我们知道进展如何:)

它们不同,但指向相同的位置。就像两张纸上都有你的家庭地址

Q3 : why b and a give same address of themselves in Q2 ? Are they same now i.e they share same location ? does b is an alias of a now ?

Q4:如果我执行b=a+1,那么打印未初始化的
b
是未定义的行为。此外,没有理由每次运行该程序时地址都应该相同。我不想要b=a我想知道的是,为什么当只包含(1)时a打印为0x22fecc,而当我包含(1)时a打印为不同的打印方式(2)然后a被打印为0x22fec8,我不在乎b打印的是什么?因为这是你第二次运行程序,地址不必与第一次相同。
Q3 : why b and a give same address of themselves in Q2 ? Are they same now i.e they share same location ? does b is an alias of a now ?
Q4 : if i do b = a+1 and then cout<< b why it gives address of a ? it should have given the address of a+1 ?