问题描述
一本关于C的书解释了一种使用任意数组索引范围的技术。
int * p = malloc(sizeof(int)* 10) - 1;
这样,分配的数组可以用索引范围1~10来访问,
不是0~9。你当然不能使用p [0]而且内存应该是
免费发布(p + 1)。
它与gcc和MSVC合作,但我不确定是否有意义采取
数组的初始元素之前的地址。有没有人有任何明确答案?
-
ES Kim
"A Book on C" explains a technique to use an arbitrary array index range.
int* p = malloc(sizeof(int) * 10) - 1;
This way, the allocated array can be accessed with index range 1 ~ 10,
not 0 ~ 9. You cannot use p[0], of course, and the memory should be
released with free(p + 1).
It worked with gcc and MSVC, but I''m not sure if it makes sense to take
the address before the initial element of an array. Does anyone have
any definite answer?
--
ES Kim
推荐答案
更正:int * p =(int *)malloc(sizeof(int)* 10) - 1;
-
ES Kim
correction: int* p = (int*)malloc(sizeof(int) * 10) - 1;
--
ES Kim
纯粹的巧合。未定义的行为。
指针可以指向一个数组对象,也可以指向一个结束对象。
-
Stan Tobias
sed's / [AZ] // g''发送电子邮件
Pure coincidence. Undefined behaviour.
A pointer can point into an array object or one past the end.
--
Stan Tobias
sed ''s/[A-Z]//g'' to email
更正:int * p =(int *)malloc(sizeof(int)* 10) - 1;
correction: int* p = (int*)malloc(sizeof(int) * 10) - 1;
不仅原来是错的,校正也是如此。你不能在对象开始之前设置一个指向该位置的指针。
上面的两行都可能导致分段错误,或者如果你是/>
少运气,未明确行为的不明显症状。
Richard
Not only is the original wrong, so is the correction. You cannot
portably set a pointer to the location before the start of an object.
Both of your lines above could cause segmentation faults, or if you''re
less lucky, more unobvious symptoms of undefined behaviour.
Richard
这篇关于任意数组索引范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!