0

I've been trying to find length of an array in C++ and wanted to make it as a function, but even if arrays are reference type sizeof function does not return same result as ran in main.

The code below returns the correct result which I need.

int main(){
    int arr[] = {3, 71, 223, 696, 21, 453, 231, 422, 22, 32};
    int max = arr[0];
    uint length = sizeof(arr) / sizeof(*arr);
    std::cout << "Length: " << length << std::endl;
    return 0;
}

The output is Length: 10, it's OK.

But if I try to make it a function, here's the example

uint getLength(int *arr){
    return sizeof(arr) / sizeof(*arr);
}

int main(){ 
    int arr[] = {3, 71, 223, 696, 21, 453, 231, 422, 22, 32};
    std::cout << "Length: " << getLength(arr) << std::endl;
    return 0;
}

It returns 2, therefore the unexpected output is Length: 2

What's causing this situation?


I found the reasonable explanation.

Firstly, I didn't know that C++ does not allow passing arrays completely.

Related to, if parameter is given as integer pointer, sizeof(arr) is constantly having value as 8 (remember integer pointer size) and sizeof(*arr) is 4 (remember integer size), because it points to first element of array.

rch
  • 127
  • 1
  • 7
  • 1
    Unrelated but I have seen this idiom to find the length a lot [`template size_t length(T(&)[N]){ return N; }`](https://godbolt.org/z/oMsKdjrz8) – Ch3steR May 15 '21 at 06:03
  • `int*` is a pointer. Full stop. Yes, in the code in the question, `arr` points at the first element of an array, but that doesn't make it an array. – Pete Becker May 15 '21 at 12:38
  • Yes, I found the reason yesterday and it's as you @Pete Becker explained. – rch May 16 '21 at 07:38

0 Answers0