CIS3355:
Business Data Structures |
How arrays are stored in RAM?
ARRAY : A data structure containing a fixed number of contiguous storage elements all of the same type.
Up to now, the only variables we have used could only one store one value at a time. However, many applications require that many values be stored simultaneously.
All the elements of an array must be the same data type, for example float, char, int, pointer to float, pointer to int, a structure or function.
Like any other variables, arrays must be declared and created before they can be used. The creation of arrays involves three steps: Declare the array Initialize the storage area Put values into the array
Type arrayname[] or type [] arrayname
Ex: int students [] or int[] students.
An array is declared in the following manner: int x [10] This reserves space in memory for 10 integers. We refer these integers as follows: x[0], x[1], ..., x[9]. Note that the first entry in an array is always indexed with a 0. Using the data type int implies that we will require 2-bytes per element
Initialization
An array is initialized to 0, false or null depending upon the type The array index starts at position 0. An array of 10 elements has index 0 to 9. We can not access positions not within the range Each value is stored at a specific position. Example: To store the heights of 6 people, we could name the heights: h1, h2, …, h6, or we can ask the compiler to allocate six memory cells to h; identified as: h[0], h[1], h[2], h[3], h[4], h[5].
Because we are specifying only one subscript or offset, we are declaring a vector (a one-dimensional array)
Arrays can also be initialized like standard variable at the time of their declaration. Type arrayname[]={list of values} Ex : int[] students = {55,69,70,30,80}
Once arrays are created, they need to be initialized with some values before access their content. For example, students [0] =50 Students [1] =40 Arrays are fixed length. Length is specified at create time.
The storage in RAM depends of the type of data.
In C++ when we store integers, they require 2 bytes per number we store. For large amounts of information storage in memory, the computer must determine:
Say we want to store an array that has the first 9 even numbers; we actually need 20 bytes of storage. That is because we also need 2 bytes for the offset. If there was 20 bytes of contiguous storage starting at 5000, the data would be listed as:
Variable Address Decimal Value even1 5000/5001 0 even2 5002/5003 2 even3 5004/5005 4 even4 5006/5007 6 even5 5008/5009 8 even6 5010/5011 10 even7 5012/5013 12 even8 5014/5015 14 even9 5016/5017 16 even10 5018/5019 18
The result in RAM would look like the following:
Notice: • The first element on the list (element number 1) has the subscript (offset) 0 (zero) • The last element on the list (element number 10) has the subscript (offset) 9 (nine).
Some good references include: http://www.cprogramming.com/tutorial/lesson8.html
|