1#include <iostream>
2#include <array> //for using std::array
3
4int main()
5{
6
7 int example[5];//array on stack
8 int* another = new int[5];//array on heap
9 delete[] another;//freeing up memory on heap
10 example[0] = 1;
11 example[1] = 2;
12 example[2] = 3;
13 example[3] = 4;
14 for (int i = 0; i < 5; i++) {
15 example[i] = 2;
16 }
17 int* ptr = example;//arrays are just pointers to the begining of the block of memory
18 example[2] = 5;
19 *(ptr + 2) = 6;//adding 4+4 bytes to ptr
20 std::cout << example[2] << std::endl;//output => 6
21 *(int*)((char*)ptr + 8) = 8;//adding 8 bytes to ptr using ptr arithmetic
22 std::cout << example[2] << std::endl;//output => 8
23 //std::array provide some additional functionality like bounce checking size checking but do have a performance overhead
24 std::array<int,5> stda;//creating an array named stda of int 5 size
25 std::cout << stda.size() << std::endl;//will output size of std::array ,output =>5
26 std::cin.get();
27}
1// Two dimensional array
2int a[2][3]= {
3 {1, 2, 3},
4 {4, 5, 6}
5 };
6
7 cout << a[1][1]; // Output is 5
8
9// Three dimensional array
10//[2] is elements; [3] is rows in elements; [4] is column in elemnents
11int a[2][3][2]= {
12 //Element 0
13 { {1, 2},
14 {2, 3},
15 {4, 5}
16
17 },
18
19
20 // Element 1
21 { {6, 7},
22 {8, 9},
23 {10, 11}
24
25 }
26 };
27
28 cout << a[0][1][1]; // Prints 3
29
1// An example of using std::array
2// Basic syntax: std::array<TYPE, SIZE> NAME;
3// Note that the size must be a constant
4
5#include <iostream>
6#include <array> // Use std::array
7
8int main() {
9 std::array<int, 10> arr;
10 arr[0] = 5; // Setting an element
11 std::cout << arr[0] << std::endl; // Element access
12 std::cout << arr.at(0) << std::endl; // Element access with bounds checking
13}