The elements of an array data structure are required to have the same size and should use the same data representation. what is the reason behind this?
-
what language are you referring to? – devlin carnate Dec 30 '15 at 16:44
-
Possible duplicate of [Java tree data-structure?](http://stackoverflow.com/questions/3522454/java-tree-data-structure) – Jake Bathman Dec 30 '15 at 16:48
-
I am referring c language. – Sonali Rangwani Jan 18 '16 at 15:24
1 Answers
It isn't possible to give an explanation that covers all languages, but what you refer to is fairly standard in languages which support arrays.
A crucial requirement that most languages have is that array access should be very efficient. This is typically done by having the elements of an array occupy a contiguous block of memory and by having all of the elements of the array take up the same size. This allows the location of any element to be determined by simple arithmetic given the index and the size of the elements.
For example, in C if you have the declaration
int a[10];
then element a[i]
is located at
&a + i*sizeof(int)
in words: the address of the first element (&
is the address operator in C and in C the address of the array is the address of the first element) plus i
times the size of the an int
.
If the elements of an array were of various sizes you would need to find some memory-consuming way of delimiting the elements and then use a search to locate the actual elements.
As an analogy, if you live on a street where each house occupies a lot of a fixed size then simple arithmetic can tell you how far you have to walk from the end of the street to a house with a given address (assuming that there are no gaps in the addresses). On the other hand, if you have large mansions interspersed with small shacks in a haphazard way then you really have no easy way to determine ahead of time how far you need to go to get to a particular address.
There are languages which seem on the surface to be more flexible. For example, the assignment A = Array(1, 2.0, "hello world")
is perfectly valid in VBA -- but what happens here is that A
is an array of Variants
-- which are structures of fixed size which include things such as type tags and pointers to the actual data.

- 51,337
- 7
- 54
- 119