So I'm doing a small task with C++ (never worked with this language before) and I encountered a problem with using 'sizeof' in an array to find its length. When I use it inside main() it works as expected, but if I use it inside a function it doesn't. It's clear that I'm missing some knowledge on very basic topics of C++ so I've come to find some guidance (I have checked the related questions of stack overflow and none provides some theory on what's happening, only ways of solving it in a different way).
I would also like to point out that I've seen different ways of making this work, but I would like to know why this one is not working and learn from it, thanks!
This is the code that I'm using:
// function example
#include <iostream>
#include <vector>
using namespace std;
// functions used
float max_value_array(float array[]);
int main()
{
float rand_vec[] = {3, 2, 7, 5, 4};
float max_num = max_value_array(rand_vec);
cout << max_num;
}
float max_value_array(float array[])
{
int len_array = sizeof(array) / sizeof(array[0]);
float max_number = array[0];
for (int i = 1; i < len_array; i++)
{
std::cout << array[i] << std::endl;
if (array[i] > max_number)
{
max_number = array[i];
}
}
return max_number;
}
(<vector>
is included because I'm using it in a different part of the code)
What I would expect from this code is to return 7
, however I'm getting 3
. Upon investigation I found out that if I return len_array
in max_value_array
I'm getting 1
(and thus, getting the first element of the array as the loop doesn't start), which means that either the vector is not correctly passed, or that operation does not work. However if I return array[3]
I get 5
, which means the array is passed correctly.
I also saw that when I return sizeof(array)
I get 4
, and the same value if I return sizeof(array[0])
(4). However, if I use cout
in the main function to log both sizeof(rand_vec)
and sizeof(rand_vec[0])
I get respectively 520 and 4, which makes me think that there is something about sizeof
and arrays that I'm not understanding.
Why does this happen?