【问题标题】:i want to understand how this part of code works [closed]我想了解这部分代码是如何工作的[关闭]
【发布时间】:2016-09-15 17:58:07
【问题描述】:

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

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

我需要理解谢谢

【问题讨论】:

  • 理解这一点的关键是b=(*ptr2)++;,它获取ptr2 所指向的内容,并在访问其值之后对其进行递增。
  • 但是 b 的值为 5 并且没有改变?为什么?
  • @blitz 了解x++++x 之间的区别。
  • 因为b = (*ptr2)++; 基本上是b = *ptr2; (*ptr2)++; 或者在这种情况下b = a; a++; 阅读后增量运算符。
  • 流程如下: 1) (*ptr2) 访问ptr2 指向的值; 2) b 设置为该值; 3) 由于您有后增量,after b 设置为 5,然后 ptr2 指向的值增加 1,现在为 6 . 如果您改为使用++(*ptr2),则该值将被访问、递增、然后分配给b

标签: c


【解决方案1】:
#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

【讨论】:

  • "// ptr2 指向 ptr1" 应该是 "Assigns ptr1 to ptr2"。 ptr2 不指向 ptr1。详细信息:可能是“先后后继”,但未定义 顺序。这更像是 2 个事件发生在 some 序列_(或没有)中,但 effect 正如您所评论的那样。如果变量访问有副作用,顺序会有所不同。
  • ptr2=ptr1 怎么样:ptr2 现在与 ptr1 拥有相同的地址。
最近更新 更多