C++指针和增量运算符(++)

最近开始为Pointer系列学习C++语言,我知道指针是具体的var,用来保存另一个变量的地址。当我们改变指针所在内存区域的值时,它也会改变那个 var 的值。所以我只是写了代码来做到这一点。

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(int argc, char const *argv[])
{
    int n=5;
    int *p=&n; //pointer p hold the address of n 
    std::cout<<"value of n = "<<n<<endl;
    std::cout<<"value of n  = "<<*p<<endl;
    std::cout<<"value of n= "<<*(&n)<<endl;
    std::cout<<"the address of n = "<<&n<<endl;
    std::cout<<"the address of n = "<<p<<endl; 
    *p=19; //change the value at the address of n -> mean n definitely change 
    std::cout<<"value of n once *p changed = "<<n<<endl;
    p++; //p address increase 4 bytes 
    std::cout<<"address of p changed  = "<<p<<endl;     
    (*p)++;
    std::cout<<"address of p   = "<<p<<endl;    

    return 0;
}

然后我得到了以下结果:

当我在图片中标记为红色时,当我执行 (*p)++ - 我知道地址 p 保持的值会增加 1,但是一旦我检查结果,它就没有显示 ( *p)++ 行,只是 p 的地址增加了 1 个字节。

这是什么原因?

回答

如果我们将您的代码分解为重要的部分,我们会看到:

int n=5; // 1.
int *p = &n; // 2.
p++; // 3.
(*p)++; // 4. Dereference and increment. 

您显然已经很好地掌握了这段代码中 1-3 的作用。但是,4是一个大问题。3、你改变了指针。之前指向的指针n,递增后,现在指向什么?无论在哪里,不一定是我们拥有的内存,可以主动改变。

在第 4 行中,您更改它。这是未定义的行为,从链接页面您可以看到:

未定义的行为 - 对程序的行为没有限制。

所以这个程序几乎可以做任何事情。


以上是C++指针和增量运算符(++)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>