Array
An array is a collection of items stored at contiguous memory locations.
- Usually starts at index 0
- Stores multiple items of same type together An array is a Pointer to the first element. think back to C++
Types of Arrays
- Linear Array
- Dynamic Array
- Multi-dimensional arrays (2D arrays)
Time Complexity of Arrays
- Indexing:
- Search:
- Insertion: n/a
- Deletion:
- Optimized Search:
Array Initialization
Zero initialized array:
Else, the values might contain some garbage values:
Full story seems a little more complex... Static Variable (file scope and function static) are initialized to zero...
Non-static variables (local variables) are indeterminate.
Reading them prior to assigning a value results in undefined behaviour.
In the case of arrays of pointers, something similar happens. I ran into this while doing this LeetCode Trie question. Question: what is the difference between using Trie* next[26] = {}
and Trie* next[26]
?
Answer: The main difference between Trie* next[26] = {}
and Trie* next[26]
is in the initialization of the array.
Trie* next[26] = {}
initializes thenext
array to allNULL
pointerTrie* next[26]
declares an array of 26 pointers toTrie
objects, but it does not initialize them to any particular value. This means that the pointers could contain garbage values, or could point to any location in memory
Initialize to a given value
Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there’s no easy way.
Don’t overlook the obvious solution, though:
Elements with missing values will be initialized to 0:
So this will initialize all elements to 0: