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

标签 c++

最近开始学习C++语言的Pointer系列,知道指针就是具体的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;
}

然后我得到了下面的结果:

C++ pointer

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

这是什么原因?

最佳答案

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

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

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

在第 4 行中,您更改它。这是 undefined behaviour其中,从链接页面您可以看到:

undefined behavior - there are no restrictions on the behavior of the program.

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

关于C++ 指针和递增运算符 (++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68172433/

相关文章:

c++ - 开源 C/C++ 3d 渲染器(支持 3ds max 模型)

c++ - Qt : which class should connect() signals and slots - inside or outside the view class?

C++ 无法在堆栈中使用 peek() 函数

c++ - 位掩码动态编程-形成对

c++ - 将 vector<char> buf(256) 转换为 LPCSTR?

c++ - 矩阵重载

c++ - 当你用完它们时你需要告诉智能指针吗

c++ - C++ CLR 值类型上需要 pin_ptr,为什么?

c++ - 实现一个没有未定义行为的类似 std::vector 的容器

c++ - erase 和 remove/remove_if 算法之间的区别?