简体   繁体   中英

C++ pointer and increment operator (++)

Recently, I begin to learn C++ language for Pointer series, I knew the pointer is the specific var what is used to hold the address of another variable. And when we change the value at the memory area which the pointer is hold, it also change the value of that var. So then i just wrote the code to do it.

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

then i got the resul below :

C++ 指针

As I mark red in my picture, when I do (*p)++ - I understood that the value at the address p hold will increase 1, but once I check the result, it didn't show the value of p after (*p)++ line , just the address of p has increased 1 byte.

What is the reason for this?

If we break down your code into the important parts, we see:

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

You clearly have a good grip on what 1-3 do in this code. But, 4 is a big problem. In 3, you changed the pointer. The pointer previously pointed to n , after incrementing, what does it point to now?Wherever it is, it is not necessarily memory that we own and can actively change.

In line 4, you change it. This is undefined behaviour which, from the linked page you can see:

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

So the program can do pretty much anything.

Your program has undefined behavior .

Let's look at this sequence picked from your program:

int n=5;
int *p=&n;
p++;       // p now points to some unknown memory area
(*p)++;    // here you dereference `p` - undefined behavior.

You are never allowed to dereference a pointer that is not pointing to an object that is "alive".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM