C 不应该';输出不是2吗
这与C 不应该';输出不是2吗,c,gdb,C,Gdb,这与main()和func()之间的堆栈不同有关吗 据我所知,指向'I'的地址被'j'覆盖了,不是吗 有人能纠正我的理解吗?在C中,参数是作为副本传递的。因此p和q是在func(&i,&j)中传递的原始地址&i和&j的副本。所以当你这样做的时候: int i = 0, j = 1; void func(int *p, int *q) { p = q; //Here the address of p and q are made same.
main()
和func()
之间的堆栈不同有关吗
据我所知,指向'I'
的地址被'j'
覆盖了,不是吗
有人能纠正我的理解吗?在C中,参数是作为副本传递的。因此
p
和q
是在func(&i,&j)中传递的原始地址&i
和&j
的副本代码>。所以当你这样做的时候:
int i = 0, j = 1;
void func(int *p, int *q)
{
p = q; //Here the address of p and q are made same.
* p = 2; // value @ address pointed by 'p'(which is q) is now set to 2.
}
int main() //Start of Main
{
func(&i, &j);
printf("%d %d n", i, j);
return 0;
}
when address held in p and q are same , i'm not understanding why the output isn't same as well (2 2).
</code>
If i fire up gdb i see the following
(gdb) p &p
$4 = (int **) 0x7fffffffebc8 <<Actual address of var p (gdb) p &q
$6 = (int **) 0x7fffffffebc0 << Actual address of var q (gdb) n 17 }
(gdb) p p
$8 = (int *) 0x601040 <j> << After the func ends its pointing only to 'j'
(gdb) p q
$9 = (int *) 0x601040 <j>
p = q; //Here the address of p and q are made same.
p
和q
现在确实是一样的,都是j
的地址。所以当你这样做的时候:
int i = 0, j = 1;
void func(int *p, int *q)
{
p = q; //Here the address of p and q are made same.
* p = 2; // value @ address pointed by 'p'(which is q) is now set to 2.
}
int main() //Start of Main
{
func(&i, &j);
printf("%d %d n", i, j);
return 0;
}
when address held in p and q are same , i'm not understanding why the output isn't same as well (2 2).
</code>
If i fire up gdb i see the following
(gdb) p &p
$4 = (int **) 0x7fffffffebc8 <<Actual address of var p (gdb) p &q
$6 = (int **) 0x7fffffffebc0 << Actual address of var q (gdb) n 17 }
(gdb) p p
$8 = (int *) 0x601040 <j> << After the func ends its pointing only to 'j'
(gdb) p q
$9 = (int *) 0x601040 <j>
p = q; //Here the address of p and q are made same.
它将p
指向的内容(即j
)设置为2
i
根本不被此修改,因此它仍然是0
。您将i
的地址作为参数p
传递,但是当您将p
设置为q
时,您立即放弃了该地址。最初在全局范围内,i和j值分别为0和1。函数调用i和j的地址(位置)时传递
* p = 2; // value @ address pointed by 'p'(which is q) is now set to 2.
在函数被调用方中,p和q保存i和j的地址。
分配时,p=q
q被分配给p,这意味着p也拥有j的地址。然后,*p=2
设置p所指地址的值。p当前指向j。所以打印时j值为2,i值保持不变。在这个场景中,我们没有任何指向i的指针。我们仅通过i修改i值
希望这会有所帮助:)理解。谢谢你,伙计,请确保你的问题得到了回答。