Closed. This question needs to be more focused。它当前不接受答案。
想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
3年前关闭。
我想了解这部分代码是如何工作的,我知道这看起来很简单,但我对指针的概念并不满意,因此任何事情都将有所帮助
输出是
我需要懂得谢谢
让我们通过地址和值表进行可视化。假设
希望全球化能有所帮助。
在此处阅读有关指针分配的信息:C++ pointer assignment
想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
3年前关闭。
我想了解这部分代码是如何工作的,我知道这看起来很简单,但我对指针的概念并不满意,因此任何事情都将有所帮助
#include<stdio.h>
int main(){
int a,b;
int *ptr1,*ptr2;
a=5;
b=a;
ptr1=&a;
ptr2=ptr1;
b=(*ptr2)++;
printf("a = %d, b=%d,*ptr1=%d,*ptr2=%d\n",a,b,*ptr1,*ptr2);
}
输出是
a = 6 , b = 5 , *ptr1 = 6 , *ptr2 = 6.
我需要懂得谢谢
最佳答案
#include<stdio.h>
int main(){
int a,b;
int *ptr1,*ptr2;
a=5; // Assigns value 5 to a
b=a; // Assigns value of a (i.e., 5) to b
ptr1=&a; // Assigns address of a to prt1 or ptr1 points to variable a
ptr2=ptr1; // ptr2 holds same address as ptr1 does (i.e, address of a)
b=(*ptr2)++;
/*
Now this one is tricky.
Look at precedence table here
http://en.cppreference.com/w/cpp/language/operator_precedence
b is assigned value of *ptr2 first and then
value at *ptr2 (i.e., 5) is incremented later.
Try replacing b = (*ptr2)++ with b = ++(*ptr2). It'll print 6.
*/
printf("a = %d, b=%d,*ptr1=%d,*ptr2=%d\n",a,b,*ptr1,*ptr2);
}
让我们通过地址和值表进行可视化。假设
int
为1字节或1单位,并且程序的地址空间以100开头。a = 5
a
+---+---+---+---+---+--
| 5| | | | | ...
+---+---+---+---+---+--
100 101 102 103 104 ...
b = a
a b
+---+---+---+---+---+--
| 5| 5| | | | ...
+---+---+---+---+---+--
100 101 102 103 104 ...
ptr1=&a
a b ptr1
+---+---+----+----+---+--
| 5| 5| 100| | | ...
+---+---+----+----+---+--
100 101 102 103 104 ...
ptr2 holds some random address when you initialize.
int *ptr2;
a b ptr1 ptr2
+---+---+----+----+---+--
| 5| 5| 100| 234| | ...
+---+---+----+----+---+--
100 101 102 103 104 ...
ptr2=ptr1
a b ptr1 ptr2
+---+---+----+----+---+--
| 5| 5| 100| 100| | ...
+---+---+----+----+---+--
100 101 102 103 104 ...
b=(*ptr2)++
First, dereference *ptr2 and assign that to b.
a b ptr1 ptr2
+---+---+----+----+---+--
| 5| 5| 100| 100| | ...
+---+---+----+----+---+--
100 101 102 103 104 ...
^ |
|____________|
Now increment value at address 100
a b ptr1 ptr2
+---+---+----+----+---+--
| 6| 5| 100| 100| | ...
+---+---+----+----+---+--
100 101 102 103 104 ...
希望全球化能有所帮助。
在此处阅读有关指针分配的信息:C++ pointer assignment
关于c - 我想了解这部分代码是如何工作的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39517490/
10-10 09:19