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

int arr[5];

➑ This array can store 5 integers
➑ Index range: 0 to 4


πŸ”Ή 2. Initialize Array with Size

int arr[5] = {10, 20, 30, 40, 50};

βœ” Size = 5
βœ” Fully initialized


πŸ”Ή 3. Partial Initialization

int arr[5] = {1, 2};

➑ Remaining elements are automatically set to 0

Result:

1 2 0 0 0

πŸ”Ή 4. Omit Array Size (Compiler Decides)

int arr[] = {5, 10, 15, 20};

βœ” Compiler sets size = 4


πŸ”Ή 5. Finding Array Size Using sizeof

Total number of elements

int arr[] = {10, 20, 30, 40};

int size = sizeof(arr) / sizeof(arr[0]);
cout << size;

Output:

4

πŸ”Ή 6. Using Array Size in a Loop

int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}


πŸ”Ή 7. Size of Character Array (String)

char name[] = "Hello";

βœ” Size = 6
➑ Includes null character '\0'

cout << sizeof(name); // 6

πŸ”Ή 8. 2D Array Size

int matrix[2][3];

➑ Rows = 2
➑ Columns = 3
➑ Total elements = 2 Γ— 3 = 6


❌ Common Mistakes

int arr[0]; // ❌ invalid
int arr[-5]; // ❌ invalid
cout << arr[5]; // ❌ out of bounds

⚠️ 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

You may also like...