Passing an array of ints as an argument in C++?
I made a function in C++ to find the length of an array. I find the sizeof
the array passed in the argument and divide it by the sizeof the variable
type. This should work but it always returns 1! Am I missing something
obvious? Or does this have to do with pointers and memory? This is my
code:
#include <iostream>
using namespace std;
int lengthOf(int arr[]);
int main() {
int x[] = {1,2,3,0,9,8};
int lenX = lengthOf(x);
cout << lenX;
return 0;
}
int lengthOf(int arr[]) {
int totalSize = sizeof arr;
cout << totalSize << endl;
int elementSize = sizeof(int);
return totalSize/elementSize;
}
Output (should be 6 instead of 1):
4
1
I am fairly new so excuse me if this is a bad question.
No comments:
Post a Comment