pointer incrementation and assignment

2020-04-14 08:17发布

In the following two lines in C:

int* a = (int *)calloc(automata_size, sizeof(int));

int* b = (a++);

I found that a and b share the same address. This is not the case if we have

int* a = (int *)calloc(automata_size, sizeof(int));

int* b = a + 1;

why?

2条回答
欢心
2楼-- · 2020-04-14 08:49

So my advice is google post-increment and pre-increment. Pre-increment (++a) is:

b = ++a;

and is the same as:

a = a + 1;
b = a;

Where as post-increment:

b = a++;

is the same as

b = a;
a = a + 1;

this applies to pointers as well as integers.

查看更多
三岁会撩人
3楼-- · 2020-04-14 08:50

The pre- and postfix ++ operators have a result and a side effect.

The result of a++ is the value of a prior to the increment. The side effect is that a is incremented. Thus, if a is something like 0x4000 and sizeof (int) is 4, then after executing

int *b = a++;

the value of b will be 0x4000 and the value of a will be 0x40041.

The result of ++a is the value of a plus 1. The side effect is that a is incremented. This time, the value of both b and a will be 0x4004.

Note: you will want to retain the original value returned from calloc somehow so that you can properly free it later. If you pass the modified value of a to free, you will (most likely) get a runtime error.


  1. Pointer arithmetic depends on the size of the pointed-to type. Applying ++ or adding 1 to a pointer advances it to point to the next object of the given type. On most systems in use today, an int is 4 bytes wide, so using ++ on a pointer adds 4 to the pointer value.

查看更多
登录 后发表回答