问题描述
如果这样:
int i,sum;
int * array;
for(sum = 0,i = 0; i< len; i ++){
sum + = array [i];
}
转换为这(暂时不介意为什么):
int i,sum;
int * array;
int * arrl ;
arl =& array [-len];
for(sum = 0,i = len; i< 2 * len; i ++){
sum + = arrl [i];
}
它应该给出相同的结果。但是有一些有趣的事情会发生。例如,如果& array是1000并且
len是100000.在这种情况下,arrl将保存一个地址
(1000-100000),这可能是因为
指针应该是unsigned int(无论int是什么大小)。
它指向的地址为MAX_POINTER - 100000 + 1000.
第二种形式循环循环开始i = len(100000)所以
arrl [100000]将回绕并指向与数组[0]相同的
位置。 br />
或者它会吗?
这种类型的数组访问似乎可能会在
之上存储器"可能会引发错误。
C标准对此有何评价(如果有的话)?
谢谢,
David Mathog
Caltech生物学部门序列分析设施经理
If this:
int i,sum;
int *array;
for(sum=0, i=0; i<len; i++){
sum += array[i];
}
is converted to this (never mind why for the moment):
int i,sum;
int *array;
int *arrl;
arl=&array[-len];
for(sum=0,i=len; i<2*len; i++){
sum += arrl[i];
}
it should give the same result. But there are some funny
things that can happen. For instance, if &array is 1000 and
len is 100000. In that case arrl will hold an address
(1000-100000) which presumably wraps around since the
pointer should be an unsigned int (whatever size int is).
The address it points to will be MAX_POINTER - 100000 + 1000.
When the second form loop loop begins i=len (100000) so
arrl[100000] will wrap back around and point to the same
place as array[0].
Or will it?
It seems possible that this sort of array access "off the top of
memory" could trigger a fault.
What does the C standard say about this (if anything)?
Thanks,
David Mathog
ma****@caltech.edu
Manager, Sequence Analysis Facility, Biology Division, Caltech
推荐答案
它说您的代码无效C.
您正在阅读哪些C书?
- Mike
It says your code is not valid C.
Which C book(s) are you reading?
-Mike
还要注意,如果你想用它们来索引(或记录大小)一个数组,对象''我'和/''' len''的类型应为''size_t'',而不是''int''。
Also note that if you want to use them to index
(or record the size of) an array, the objects ''i''
and ''len'' should be of type ''size_t'', not ''int''.
嗯,为什么用作数组索引的变量是
类型''size_t''? K& R-2nd / ANSI使用''int''经常
来索引数组。
案例
Huh, why should a variable used as array index be of
type ''size_t''? K&R-2nd/ANSI uses ''int'' quite often
to index arrays.
Case
帮自己一个忙,阅读常见问题解答。不要回来,直到你已经完成它了!
Dan
-
Dan Pop
DESY Zeuthen,RZ集团
电子邮件:
这篇关于关于阵列访问环绕标准的标准是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!