C++ Array Size
π C++ Array Size
In C++, array size means the number of elements an array can store.
Array size is fixed and must be known at compile time (for static arrays).
πΉ 1. Declaring Array with Size
β‘ This array can store 5 integers
β‘ Index range: 0 to 4
πΉ 2. Initialize Array with Size
β Size = 5
β Fully initialized
πΉ 3. Partial Initialization
β‘ Remaining elements are automatically set to 0
Result:
πΉ 4. Omit Array Size (Compiler Decides)
β Compiler sets size = 4
πΉ 5. Finding Array Size Using sizeof
Total number of elements
Output:
πΉ 6. Using Array Size in a Loop
πΉ 7. Size of Character Array (String)
β Size = 6
β‘ Includes null character '\0'
πΉ 8. 2D Array Size
β‘ Rows = 2
β‘ Columns = 3
β‘ Total elements = 2 Γ 3 = 6
β Common Mistakes
β οΈ Accessing outside the array leads to undefined behavior.
π Array Size vs Vector Size
| Array | Vector |
|---|---|
| Fixed size | Dynamic size |
sizeof needed |
v.size() |
| Faster | Safer & flexible |
π Summary
-
Array size is fixed
-
Index starts from
0 -
Use
sizeof(arr)/sizeof(arr[0])to get length -
Character arrays include
'\0' -
For dynamic size, use
vector
