指针增加和分配 [英] pointer incrementation and assignment
问题描述
在C的以下两行中:
int* a = (int *)calloc(automata_size, sizeof(int));
int* b = (a++);
我发现a和b共享相同的地址.如果有的话不是这样
int* a = (int *)calloc(automata_size, sizeof(int));
int* b = a + 1;
为什么?
前缀和后缀++
运算符具有结果和副作用.>
a++
的结果是增量之前的a
值. 副作用是a
递增.因此,如果a
类似于0x4000
且sizeof (int)
为4,则在执行后
int *b = a++;
b
的值将为0x4000
,a
的值将为0x4004
1 .
++a
的结果是a
的值加1.副作用是a
递增.这次,b
和a
的值都将为0x4004
.
注意:您将希望保留以某种方式从calloc
返回的原始值,以便以后可以正确地free
使用它.如果将修改后的a
值传递给free
,则(很可能)会出现运行时错误.
- 指针算术取决于指向类型的大小.将
++
或加1到指针将其前进,使其指向给定类型的下一个对象.在当今使用的大多数系统上,int
的宽度为4个字节,因此在指针上使用++
会将指针值加4.
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?
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 0x4004
1.
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.
- 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, anint
is 4 bytes wide, so using++
on a pointer adds 4 to the pointer value.
这篇关于指针增加和分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!