0
Determining array size automaticly
I try to write a function that returns array length using sizeof(x)/sizeof(x[0]) . The idea was to just wrap the function around this : int length(int x[]){ return sizeof(x)/sizeof(x[0]) ; } However the function returns the size of int instead of acessing the entrie array. How can I fix this?
4 Answers
+ 2
you can get to this by passing a reference to an array to capture the size of the array at compile time:
https://code.sololearn.com/cm4xRuCEoI7m/#cpp
+ 1
Passing 'int x[]' to the function just passes an adress to the first element of that array..There's no way of knowing its length unless you pass it as an argument too..
Just use "std::size()" method to get the size for stack allocated arrays i.e 'std::size(x) or x.size()'
+ 1
How do I use this? Sorry, but I'm quite new to C++. Arrayname has to be replaced by the name of the array, right? But then it still does not work, do I have to put () behind? That does not work either. And does it work from within a function, where the array is only represented by a pointer to that array?
+ 1
Hope dis example helps
int a[10];
size_t size_of_array = sizeof(a); // Size of array a
int n = sizeof (a) / sizeof (a[0]); // Number of elements in array a
size_t size_of_element = sizeof(a[0]); // Size of each element in array a
// Size of each element = size of type