I am a new student in c programming, and I made a small program to see in the action, all the combinations of ++ in the pointers. So I codded: (i run it in Ubuntu via virtualbox)

 #include <stdio.h>

 main()
 {
    int num = 1;
    int  *p = &num;

    printf("\nnum position: %p num value: %d\n", p, num);

    *p += 1;
    printf("\n---- *p += 1; -----\n");
    printf("num position: %p num value: %d\n", p, num);

    *p++;
    printf("\n---- *p++; -----\n");
    printf("num position: %p num value: %d\n", p, num);

    (*p)++;
    printf("\n---- (*p)++; -----\n");
    printf("num position: %p num value: %d\n", p, num);

    ++(*p);
    printf("\n---- ++(*p); -----\n");
    printf("num position: %p num value: %d\n", p, num);

    ++*p;
    printf("\n---- ++*p; -----\n");
    printf("num position: %p num value: %d\n\n", p, num);

 }

Output:

num position: 0xbfce07b8 num value: 1

---- *p += 1; -----
num position: 0xbfce07b8 num value: 2

---- *p++; -----
num position: 0xbfce07bc num value: 2

---- (*p)++; -----
num position: 0xbfce07bd num value: 2

---- ++(*p); -----
num position: 0xbfce08bd num value: 2

---- ++*p; -----
num position: 0xbfce08bd num value: 2

I have understood the different usage of ++. However my question is about the addresses (i just write the 4 digits)

At first the address is : 07b8
after the 1st increment the address is 07bc (increased by 4 (HEX) )
after the 2nd increment the address is 07bd (increased by 1 (hex))
after the 3nd increment the address is 08bd (increased by 100 (hex))

Why the increment of the address isn't stable?

有帮助吗?

解决方案

Your program has undefined behavior: your code cannot write to *p after it has been advanced, because at that point the pointer points to memory not allocated to an int. Because of the way your variables are declared it appears that after the first increment the pointer is actually pointing to itself! Printing the address of the pointer &p should confirm that.

To fix this issue, change your program as follows:

int data[] = {0,0,0,0,0,0,0,0,0,0};
int *p = data;

Now you can increment your pointer up to ten times without the risk of writing to memory outside of the range allocated to your program.

Note: %p expects a void* pointer, so you should insert an explicit cast.

其他提示

This happens because generally the memory isn't allocate sequentially by the O.S. As a start you can read more here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top