Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the elements of an array guaranteed to be stored from lower to higher addresses?

Suppose I have the following array:

int list[3]={2,8,9};
printf("%p,%p,%p",(void*)&list[0],(void*)&list[1],(void*)&list[2]);

Is it always guaranteed that &list[0]<&list[1]<&list[2] ?

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

Little endian or Big endian

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.

like image 478
Rüppell's Vulture Avatar asked May 06 '13 10:05

Rüppell's Vulture


People also ask

How are elements in an array stored?

When we declare an array, space is reserved in the memory of the computer for the array. The elements of the array are stored in these memory locations. The important thing about arrays is that array elements are always stored in consecutive memory locations.

How does an array stores its elements in memory?

An array stores its elements in contiguous memory locations. If You created the array locally it will be on stack. Where the elements are stored depends on the storage specification.

Are array elements contiguous?

So array elements are contiguous in memory and therefore do not require any metadata.

Can we store two elements in the same array location in memory?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.


1 Answers

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

However, it is not guaranteed that the values printed by printf with %p will also follow the same ordering - these values are implementation-defined.

like image 51
interjay Avatar answered Oct 25 '22 22:10

interjay