1int nums[100] = {0}; // initiallize all values to 0
2
3int nums[5] = {1,2,3,4,5};
4
5// type name[size] = {values};
1#include <iostream>
2using std::cout;
3
4int a[] = { 1, 2, 3, 4, 5 };
5int counta()
6 {
7 return sizeof( a ) / sizeof( a[ 0 ] ); // works, since a[] is an array
8 }
9
10int countb( int b[] )
11 {
12 return sizeof( b ) / sizeof( b[ 0 ] ); // fails, since b[] is a pointer
13 }
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// 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}