<div id='stars2'></div> <div id='stars3'></div> <div id='stars4'></div> [[Programming#Section 1 Foundation|Learn Programming Section 1]] previous: [[Iteration - Loops]] --- 1. general definition 2. static vs dynamic arrays 3. access 4. init 1. partial init 5. passing arrays 6. 1d vs 2d vs N-d arrays 1. memory layout 2. access 7. Pointer Arithmetic ## What is an Array An Arrays is a variable that can store multiple values of the specified type. ### Declaration ```cpp type name[size]; int letters[26]; float distance[50]; ``` ### Access Accessing elements of an array are done by using an offset. - The first element will have an offset of 0 - The last element will be the total elements minus one ```cpp // Here we have an array with 10 elements int numbers[15]; // first element int FirstNumber = numbers[0]; //last element int LastNumber = numbers[14]; //This gives an error for being out of bounds int wrong = numbers[15]; ``` > [!Warning] > To reiterate there is no bounds checking when accessing arrays! Writing to the array works the same. ```cpp numbers[5] = 123; numbers[0] = 54; numbers[14] = 12; ``` Using loops ```cpp const int ArraySize = 10; int numbers[ArraySize]; for(int i = 0; i < ArraySize; ++i) { numbers[i] = i; } ``` ### Initialize Arrays By default the values of an array are uninitialized. Usually there won't be anything there but you should stay on the safe side and just initialize it. You can assign default values in the declaration ```c++ float coins[10] {}; //inits all values to 0 int fruit[3] {62, 7, 31}; int moreFruit[3] = {4, 17, 42}; ``` or do so after the declaration ```c++ float fruit[3]; for(int i = 0; i < 3; i++) fruit[i] = 0; //or whatever other value you want ``` ```cpp int numbers[3] = {1,2,3}; int numbers[5] = {1,2,3}; // 4th, and 5th element default to 0 int numbers[] = {1,2,3}; // creates an array to match size of provided paramters , in this case 3 int numbers[3] = {1,2,3,4}; // ERROR int numbers[100] = {0}; //Inits all elements to 0 ``` ## Static vs Dynamic Arrays ### Static All of the arrays in the above examples would be static arrays. The size of these arrays is determined at compile time and cannot be changed later. ### Dynamic Dynamic arrays can have their size changed later but take more work to manage. ## 1d vs 2d vs N-d Arrays Most arrays will use just a single dimension. Some data though is easier to use with multiple dimensions. The most common being spatial data(grids, longitude/latitude, etc.) ```cpp int position[100][100]; //2d int position[100][100][100]; //3d ``` ### Memory Layout Under the hood though multidimensional arrays are still stored as a 1d array. It's not too uncommon to use a 1d array as a N-d array. ```cpp const int width = 5; int array[25]; //treats array as a 5x5 2d array for(int y = 0; y < 5; y++) for(int x = 0; x < 5; x++ ) array[ y*width + x] = 0; ``` Usually this is done in cases where processing the data sequentially is more efficient. # ---- next: [[Code Style]]