dbconfession dbconfession - 1 month ago 7
C Question

Are "array" element values stored in one location or in separate locations?

Since there's no such thing as an array in the C language, is the following all stored in one memory location, or is each element's value stored in an "array" of memory locations?

int array[] = {11, 13, 17, 19};


scenario 1

{11, 13, 17, 19} --> location A


scenario 2

{
11 --> location A
13 --> location B
17 --> location C
19 --> location D
}

Answer

C explicitly defines "array" as a type.

Quoting C11, chapter §6.2.5, Types (emphasis mine)

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. Array types are characterized by their element type and by the number of elements in the array. An array type is said to be derived from its element type, and if its element type is T, the array type is sometimes called ‘‘array of T’’. The construction of an array type from an element type is called ‘‘array type derivation’’.

In a nutshell, the answer is, array elements are stored in seperate but contiguous locations.

See the below image for clarification

enter image description here

So the representation

{
    11 --> location A
    13 --> location B
    17 --> location C
    19 --> location D
}

is valid, considering B == A + sizeof (datatype), C == B + sizeof (datatype) and so on.