Why Do We Need Array Size as an Argument?
Tehtävä
Swipe to start coding
Why is it necessary to provide the size of the array as an additional argument when using dynamic arrays? The crucial factor is that technically, we are passing not the entire array but the pointer to its first value.
Remember
The compiler does not have information about the size of the array, which can lead to accessing memory beyond the array's boundaries, resulting in unexpected garbage values.
Let's solve a simple task to illustrate it:
- Pass the dynamic array as the first argument of the function.
- Call the function inside the
main()
block and pass the pointer at the first element of the array as the first argument.
Look at the result! Pay attention to the last two values!
Ratkaisu
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
// Function to read the content of a dynamic array without passing the size
void readDynamicArray(int* arr) {
// Read the next 7 values in memory, which are situated after the initial element of the array.
for (int index = 0; index < 7; index++) {
// Attempt to read data beyond the array's boundary at indexes 5 and 6
std::cout << "Value at index " << index << ": " << *(arr + index) << std::endl;
}
}
int main() {
// Dynamically allocate an array with 5 integers
int* dynamicArray = new int[5];
// Initialize the dynamic array
for (int i = 0; i < 5; ++i)
dynamicArray[i] = i * 10;
// Call the function to read the dynamic array
readDynamicArray(dynamicArray);
// Deallocate the dynamic array to prevent memory leaks
delete[] dynamicArray;
}
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 2. Luku 6
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
// Function to read the content of a dynamic array without passing the size
void readDynamicArray(___ arr)
{
// Read the next 7 values in memory, which are situated after the initial element of the array.
for (int index = 0; index < 7; index++) {
// Attempt to read data beyond the array's boundary at indexes 5 and 6
std::cout << "Value at index " << index << ": " << *(arr + index) << std::endl;
}
}
int main()
{
// Dynamically allocate an array with 5 integers
int* dynamicArray = new int[5];
// Initialize the dynamic array
for (int i = 0; i < 5; ++i)
dynamicArray[i] = i * 10;
// Call the function to read the dynamic array
readDynamicArray(___);
// Deallocate the dynamic array to prevent memory leaks
delete[] dynamicArray;
}
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme