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.