指针增加和分配 [英] pointer incrementation and assignment

查看:89
本文介绍了指针增加和分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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类似于0x4000sizeof (int)为4,则在执行后

int *b = a++;

b的值将为0x4000a的值将为0x4004 1 .

++a结果a的值加1.副作用a递增.这次,ba的值都将为0x4004.

注意:您将希望保留以某种方式从calloc返回的原始值,以便以后可以正确地free使用它.如果将修改后的a值传递给free,则(很可能)会出现运行时错误.


  1. 指针算术取决于指向类型的大小.将++或加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 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.

这篇关于指针增加和分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆