I'm new to pointers, and want to learn them.
I created a script that should adopt Python's len()
function for arrays to get the size of them for learning reasons. So I wrote the following code:
int len(int *arrPtr){
int arrSize = *(&arrPtr + 1) - arrPtr;
return arrSize;
}
int main(){
int arr[] = {1,2,3,4,5};
int lenArr = len(arr);
cout << "lenght of array: " << lenArr;
}
When I execute the code, I get a random number:
I tried to find the solution but I failed. I found out that by increasing the array's pointer index address by 1, I get a different address, when inside the function or outside the function. In the main()
function, the same code works.
#include <iostream>
using namespace std;
int len(int *arrPtr){
cout << "inside func: " << arrPtr << endl;
cout << "inside func: " << &arrPtr + 1 << '\n' << endl;
int arrSize = *(&arrPtr + 1) - arrPtr;
return arrSize;
}
int main(){
int arr[] = {1,2,3,4,5};
cout << "outside func: " << arr << endl;
cout << "outside func: " << &arr + 1 << '\n' << endl;
int lenArr = len(arr);
cout << "lenght of array: " << lenArr;
}
Here is the code with the outputs of the changing address:
terminal output:
outside func: 0x1f961ffb90
outside func: 0x1f961ffba4
inside func: 0x1f961ffb90
inside func: 0x1f961ffb78
lenght of array: 444072222
and there is the output, as we can see the addresses change differently:
I hope someone can give me a solution.