pointer incrementation and assignment

后端 未结 2 1254
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 23:39

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 addre

2条回答
  •  我在风中等你
    2021-01-22 00:34

    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.

提交回复
热议问题