0

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:

image

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

0

This is how you can handle array sizes :

#include <array>
#include <iostream>
//using namespace std; // don't do this.

template<std::size_t N>
void function(const int(&arr)[N])
{
    std::cout << "std::array from function, len = " << N << "\n";
    std::cout << "arr[2] = " << arr[2] << "\n";
}

void function2(const std::array<int, 5>& arr)
{
    std::cout << "std::array from function2, len = " << arr.size() << "\n";
    std::cout << "arr[2] = " << arr[2] << "\n";
}

int main()
{
    int arr[] = { 1,2,3,4,5 };

    auto len1 = sizeof(arr) / sizeof(int); // do it where the size of the array is still known.
    std::cout << "len 1 =  " << len1 << "\n";
    function(arr);

    // or use std::array which behaves more like any other class
    // and which always knows its size

    std::array<int, 5> arr2{ 1,2,3,4,5 };
    std::cout << "std::array len = " << arr2.size() << "\n";

    function2(arr2);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • You beat me to it :-). Consider using `sizeof(arr[0])` or `sizeof(*arr)` instead of `sizeof(int)`; that makes that code more flexible and general. – Walter Oct 10 '21 at 19:03
  • @Walter I agree with your remark, though I stopped using that kind of array size calculation a long time ago and only use other the techniques (together with range based for loops) where I can. – Pepijn Kramer Oct 11 '21 at 03:21