0

I am currently trying to implement a function (somewhat similar to Python's builtin one) that finds the length of an array.

This is my implementation: (don't mind the other "includes")

#include <iostream>
#include "List.hpp"
#include "testClass.hpp"
#include "Coordinate.hpp"

int len(int arr[]);

int main() {
    int arr[3] = {1, 2, 3};
    std::cout << len(arr) << std::endl;
}

int len(int arr[]) {
    return sizeof(arr)/sizeof(arr[0]);
}

But this produces

main.cpp: In function 'int len(int*)':
main.cpp:16:22: warning: 'sizeof' on array function parameter 'arr' will return size of 'int*' [-Wsizeof-array-argument]    
     return sizeof(arr)/sizeof(arr[0]);
                      ^
main.cpp:14:17: note: declared here
 int len(int arr[])
             ^

However, copy+pasting the body of len into main,

#include <iostream>

int len(int arr[]);

int main() {
    int arr[3] = {1, 2, 3};
    std::cout << sizeof(arr)/sizeof(arr[0]) << std::endl;
}

int len(int arr[]) {
    return 0;
}

works a produces the desired result: 3.

My question is, why does the latter work, but not the former? And how would I reimplement the former to print 3?

EDIT: Upon reading the below comments, its obvious why this doesn't work, and that there's no way to do this, unless I use a vector, which already has a .size() method anyway.

VSCloud9
  • 75
  • 11
  • When you pass an array as a parameter, it decays into a pointer, so you won't be able to find its actual length. – mediocrevegetable1 Mar 15 '21 at 02:59
  • *I am currently trying to implement a function (somewhat similar to Python's builtin one) that finds the length of an array.* -- So after 4 decades of C and C++, you have a breakthrough function to determine the length of an array when given just a pointer? Pointers only know one thing -- that they point to a single value -- nothing more, nothing less. The only thing that knows that the pointer actually points to a value, followed by another valid value, followed by another valid value, etc. is you, the programmer. – PaulMcKenzie Mar 15 '21 at 03:48
  • That's why `std::array` was created, so as a way to wrap this in a class and pass the class around instead of a mere pointer. – PaulMcKenzie Mar 15 '21 at 03:51

0 Answers0