9. Arrays And Strings

An array is a list consisting of the same data types. The array elements are stored in contiguous locations in the memory, which makes it easy to access array elements. The following defines an integer array of three elements, and each element of this array occupies 4 bytes in the memory (because an integer is 4 bytes in length):

int nums[3] = {1, 2, 3}

The array name nums is a pointer constant that points to the first element of the array (that is, the array name points to the base address of the array). In a high-level language, to access the elements of the array, you use the array name along with the index. For example, you can access the first element using nums[0], the second element using nums[1], and so on:

In assembly language, the address of any element in the array is computed using three things:

  • The base address of the array
  • The index of the element
  • The size of each element in the array

When you use nums[0] in a high-level language, it is translated to [nums+0*<size_of_each_element_in_bytes>], where 0 is the index and nums represents the base address of the array. From the preceding example, you can access the elements of the integer array (the size of each element is 4 bytes) as shown here:

nums[0] = [nums+0*4] = [0x4000+0*4] = [0x4000] = 1
nums[1] = [nums+1*4] = [0x4000+1*4] = [0x4004] = 2
nums[2] = [nums+2*4] = [0x4000+2*4] = [0x4008] = 3

A general form for the nums integer array can be represented as follows:


nums[i] = nums+i*4

The following shows the general format for accessing the elements of an array:

[base_address + index * size of element]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.255.127