我定义了一个变量 p,它是一个指针,然后在指针上添加一个,这让我感到困惑的是 p 和 * p 是一样的。

Following are my code:

int main(){
    int *p;
    int a=1;
    p=&a;
    p++;
    printf("%p\n",p);
    //int b=*p;
    printf("%d\n",*p);
    return 0;
}

Following is the result: enter image description here

When I added the sentence *int b=p,I find p and *p is diffrent again; Following is the result: enter image description here

转载于:https://stackoverflow.com/questions/53038383/i-define-a-variable-p-which-is-a-pointer-then-i-add-one-to-the-pointer-which-con

It's undefined what your p and *p will be actually.

From your experiments, seems like p points to itself after the p++ operation. As I do not have your compiled assemble or your stack dumping, its just a guess, but with reasons:

  • As a int pointer, p will point to the address right after a after the p++ operation. If the compiler has put int a=1; at the start of current frame (as it's a constant), then int *p may be next to a.

  • p has the same value as *p, that make my previous gussing makes sence.

When you increment the pointer it points to a random piece of memory.

The value of this memory address, and the contents of it, may change every time you run the program.

The extra line you add changes the random values because anything could change them. The execution details of the line don't matter.

int main() {
    int *p;
    int a=1;
    p=&a; // pointer p points to the integer variable a
    p++;  // pointer p points to a random piece of memory
    printf("%p\n",p);  // This is a memory address, it will change with each run
    printf("%d\n",*p); // This is the contents of a random piece of memory
    return 0;
}

In your stack, you have 2 variables:

Offset_from_top_of_the_stack variable
-sizeof(int*)                    p      
-(sizeof(int*) + sizeof(int))    a

p is set to the address of a. Then you increment it by 1, it points to p itself.

And the address of p in memory happens to be less than sizeof(int) and your machine is a little-endian one, or your machine is a x32 one which sizeof(int*) == sizeof(int), which leads to p == *p.

the symbol * has diffent meanings in deffent place.

int *p define a point type variable it just save memory address not a value.

int b = *p means take value from p's memory address.

I think c language is not friendly for new programmer, you need to learn a lot of computer science , and know a lot of computer's details , after that you can start to learn c language.

but in Chinese education system , the first thing is learn c language , it's a bad learning roadmap for students.