我想了解这部分代码是如何工作的

时间:2016-09-15 17:58:07

标签: c

我想了解代码的这一部分是如何工作的我知道它看起来很简单,但是指针概念并不好,所以任何事情都会有所帮助

EXPLAIN

,输出

 #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);
    }

我需要知道谢谢

1 个答案:

答案 0 :(得分:4)

#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  ...

希望vizulization有所帮助。

在此处阅读指针分配:C++ pointer assignment