数组的元素是否保证从低地址到高地址存储? [英] Are the elements of an array guaranteed to be stored from lower to higher addresses?
问题描述
假设我有以下数组:
int list[3]={2,8,9};
printf("%p,%p,%p",(void*)&list[0],(void*)&list[1],(void*)&list[2]);
是否始终保证 &list[0]<&list[1]<&list[2] ?
在使用 C 时,我曾认为这是一个硬性规定,但现在必须非常确定,因为当我回答他关于 endianness
的问题时,OP 刚刚问过我这个问题
I had assumed it to be a hard and fast rule while using C, but now have to very sure about it as an OP just asked me about it when I answered his question about endianness
让我重新思考的是 stacks can grow up or down
问题.我对此不太确定,因此非常感谢您的严谨回答.谢谢.
What gave me second thoughts is the stacks can grow up or down
issue.I am not very sure about that so your rigorous answers are appreciated.Thanks.
推荐答案
是的,保证 &list[0]<&list[1]
和 &list[1]<&list[2]
.当比较指向同一数组元素的指针时,指向具有较大下标的元素的指针将被认为具有较大的值.这是在 C99 6.5.8@5 中指定的:
Yes, it's guaranteed that &list[0]<&list[1]
and &list[1]<&list[2]
. When pointers to elements of the same array are compared, the pointer to the element with the larger subscript will be considered to have larger value. This is specified in C99 6.5.8@5:
指向具有较大下标值的数组元素的指针比指向具有较小下标值的相同数组元素的指针更大
pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values
但是,不能保证 printf 使用 %p
打印的值也将遵循相同的顺序 - 这些值是实现定义的.
However, it is not guaranteed that the values printed by printf with %p
will also follow the same ordering - these values are implementation-defined.
这篇关于数组的元素是否保证从低地址到高地址存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!