I want to calculate the length of an array inside a function, to use it for iteration. But the normal pointer method to calculate the array isnt working. Why? What changes can i make to my code to make it work? Im aware there are much better ways to go about getting the length, or to print the array, but what is fundamentally wrong in this method?
#include <iostream>
using namespace std;
void print(int ar[]){
int len = *(&ar + 1) - ar;
for(int i = 0; i < len; i++){
cout << ar[i] << ' ';
}
cout << endl;
}
int main() {
int aa[] = {2,3,1};
print(aa);
}
Output of the above code is a blank line (only endl
is being print)
When I write cout << len;
inside the function, the output turns out to be -4292483
, which seems like a random number.