c++ - What happens at a hardware level when I access an element of an array? -
int arr [] = {69, 1, 12, 10, 20, 113};
what happens when
int x = a[3];
????
i under impression a[3]
meant like:
"start @ memory address arr
. walk 3 memory addresses forward. integer represented @ memory address."
but i'm confused how hash tables work. because if hash tables implemented array of "buckets" (like professor says in lecture: https://www.youtube.com/watch?v=upo-m8bzrrc), still have walk bucket need; hence, no more efficient access array be.
can clear me?
imagine memory big, two-column table:
+---------+-------+ | address | value | +---------+-------+ | ... | ... | +---------+-------+ | 100 | 69 | <-- &arr[0] 100 +---------+-------+ | 101 | 1 | +---------+-------+ | 102 | 12 | +---------+-------+ | 103 | 10 | <-- &arr[3] 103 +---------+-------+ | 104 | 20 | +---------+-------+ | 105 | 113 | +---------+-------+ | ... | ... | +---------+-------+
i want emphasize highly simplified model, should give idea of going on. computer knows array begins at, let's address 100. and, because of elements in given array same size, can access third element of array adding +3 beginning address. computer not need "walk" third element of array, grabs value stored in memory @ address 100 + 3.
if want see example of in action, compile , run following code:
#include <iostream> using namespace std; int main() { int a[] = { 1, 2, 3 }; cout << "address of a:\t\t" << &a[0] << endl; cout << "address of a[2]:\t" << &a[2] << endl; return 0; }
make note of address of a. assuming computer using 32-bit integers, should see address of a[2] address of a + 2*4. reason adds 2*4 , not 2 because each integer uses 4 bytes of memory (i.e. single value span 4 addresses).
Comments
Post a Comment