Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Array Size and Boundaries | Working with Array Elements
C++ Arrays

bookArray Size and Boundaries

Note
Definition

Pointer Decay
When an array is passed to a function, it is treated as a pointer, losing its size information.

Understanding the size of an array and respecting its boundaries is essential for safe and correct programming in C++. An array's size determines how many elements you can safely access. Accessing elements outside the valid range—known as out-of-bounds access—can lead to unpredictable behavior, crashes, or subtle bugs. In C++, arrays do not carry size information with them, so you must keep track of their size yourself. This makes it especially important to know how to determine the size of an array and to use this information correctly when working with array elements.

main.cpp

main.cpp

copy
123456789101112131415
#include <iostream> int main() { int numbers[] = {10, 20, 30, 40, 50}; // Calculate the number of elements in the array size_t arraySize = sizeof(numbers) / sizeof(numbers[0]); std::cout << "Array size: " << arraySize << std::endl; std::cout << "Array elements: "; for (size_t i = 0; i < arraySize; ++i) std::cout << numbers[i] << " "; std::cout << std::endl; }

In the code above, you see how to determine the number of elements in a local array using the sizeof operator. sizeof(numbers) gives the total number of bytes used by the array, while sizeof(numbers[0]) gives the number of bytes used by one element. Dividing these values gives the total number of elements. This technique works only for arrays declared in the same scope, such as local arrays. If you pass an array to a function, sizeof will not give you the correct result because the array decays to a pointer, losing its size information.

main.cpp

main.cpp

copy
12345678910111213141516
#include <iostream> void printArraySize(int arr[]) { // Attempt to calculate the size inside the function size_t sizeInFunction = sizeof(arr) / sizeof(arr[0]); std::cout << "Size inside function: " << sizeInFunction << std::endl; } int main() { int numbers[] = {1, 2, 3, 4, 5}; size_t sizeInMain = sizeof(numbers) / sizeof(numbers[0]); std::cout << "Size in main: " << sizeInMain << std::endl; printArraySize(numbers); }

When you pass an array to a function, it is treated as a pointer. This means sizeof(arr) inside the function gives you the size of a pointer, not the size of the entire array. As a result, the calculation for the number of elements is incorrect within the function. This phenomenon is known as pointer decay and can lead to bugs if you try to determine the array's size inside a function using sizeof. To safely handle array sizes in functions, you should pass the array's size as a separate parameter or use modern C++ containers that keep track of their own size.

question mark

Why does sizeof not work to get the array size inside a function?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

Can you explain what pointer decay means in more detail?

How should I pass the size of an array to a function in C++?

What are some modern C++ containers that handle their own size?

bookArray Size and Boundaries

Свайпніть щоб показати меню

Note
Definition

Pointer Decay
When an array is passed to a function, it is treated as a pointer, losing its size information.

Understanding the size of an array and respecting its boundaries is essential for safe and correct programming in C++. An array's size determines how many elements you can safely access. Accessing elements outside the valid range—known as out-of-bounds access—can lead to unpredictable behavior, crashes, or subtle bugs. In C++, arrays do not carry size information with them, so you must keep track of their size yourself. This makes it especially important to know how to determine the size of an array and to use this information correctly when working with array elements.

main.cpp

main.cpp

copy
123456789101112131415
#include <iostream> int main() { int numbers[] = {10, 20, 30, 40, 50}; // Calculate the number of elements in the array size_t arraySize = sizeof(numbers) / sizeof(numbers[0]); std::cout << "Array size: " << arraySize << std::endl; std::cout << "Array elements: "; for (size_t i = 0; i < arraySize; ++i) std::cout << numbers[i] << " "; std::cout << std::endl; }

In the code above, you see how to determine the number of elements in a local array using the sizeof operator. sizeof(numbers) gives the total number of bytes used by the array, while sizeof(numbers[0]) gives the number of bytes used by one element. Dividing these values gives the total number of elements. This technique works only for arrays declared in the same scope, such as local arrays. If you pass an array to a function, sizeof will not give you the correct result because the array decays to a pointer, losing its size information.

main.cpp

main.cpp

copy
12345678910111213141516
#include <iostream> void printArraySize(int arr[]) { // Attempt to calculate the size inside the function size_t sizeInFunction = sizeof(arr) / sizeof(arr[0]); std::cout << "Size inside function: " << sizeInFunction << std::endl; } int main() { int numbers[] = {1, 2, 3, 4, 5}; size_t sizeInMain = sizeof(numbers) / sizeof(numbers[0]); std::cout << "Size in main: " << sizeInMain << std::endl; printArraySize(numbers); }

When you pass an array to a function, it is treated as a pointer. This means sizeof(arr) inside the function gives you the size of a pointer, not the size of the entire array. As a result, the calculation for the number of elements is incorrect within the function. This phenomenon is known as pointer decay and can lead to bugs if you try to determine the array's size inside a function using sizeof. To safely handle array sizes in functions, you should pass the array's size as a separate parameter or use modern C++ containers that keep track of their own size.

question mark

Why does sizeof not work to get the array size inside a function?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2
some-alt