1

Why am i getting a garbage value when finding the length of the array using pointer inside the function but it is working fine in main function
here is the code:

#include<iostream>
#include<array>

using namespace std;

class fun
{
public:
    void lead(int arr[]) {
        cout << "empty" << endl;
    }
    int len(int arr[]) {
        int size = *(&arr + 1) - arr;
        return size;
    }

};

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

    cout << *(&arr + 1) - arr; // working as expected

    fun obj;
    int size = obj.len(arr);
    cout << size; // giving garbage value
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 3
    A "C" style array the way you use it doesn't have a length. Use std::vector or std::array those both have lengths. – Pepijn Kramer Feb 08 '23 at 13:45
  • 2
    you cannot "find the lenght of an array using a pointer". There is no such thing. Arrays are not pointers and pointers are not arrays. Arrays have a size, pointers point to one thing – 463035818_is_not_an_ai Feb 08 '23 at 13:45
  • This is sort of clever `int size = *(&arr + 1) - arr;` but misses the point. `arr` is a pointer to the first element not a pointer to the array – 463035818_is_not_an_ai Feb 08 '23 at 13:46
  • A side note: better to avoid `using namespace std` - see here https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – wohlstad Feb 08 '23 at 13:46
  • You can change it to `template size_t len(const int (&arr)[N]) {return N;}` https://godbolt.org/z/q9WKK9edY – mch Feb 08 '23 at 13:50
  • `&arr` is the place of the pointer to `arr` so `*(&arr + 1)` Is the thing happens to be after the pointer. This is undefined. The fact it worked once is just an accident, (Even if it works reliably for arrays on the stack from the same function it may not work on a different computer or after a compiler-update) – Botond Horváth Feb 08 '23 at 13:51
  • `int len(int arr[])` -- This is *exactly* the same as this: `int len(int* arr)`. Does that clear up the issue? The `[]` in the parameter list does not give you an array -- it is just convenient, syntactic sugar. – PaulMcKenzie Feb 08 '23 at 13:54
  • In `main`, `&arr` is an `int (*)[7]` - a pointer to an array with seven `int`s. In `len`, `&arr` is an `int**` - a pointer to a pointer to an `int`. But note that dereferencing `&arr + 1` is undefined in either case. – molbdnilo Feb 08 '23 at 13:54
  • Also, if passing arrays like this actually worked, instead of a cryptic `*(&arr + 1) - arr`, after 25+ years of being standardized, I would have expected that the C++standard would have had a convenient, standard function to do this. – PaulMcKenzie Feb 08 '23 at 13:59
  • You forgot to pass the size of the array, `void lead(int arr[], size_t arr_size)`. – Eljay Feb 08 '23 at 14:05

0 Answers0