When you pass an array as an argument to a function, the array variable is converted into a pointer to an array.
Therefore, sizeof
will not return the number of bytes in the array, it will return the number of bytes in a pointer. You must pass the length of the array as a separate variable or include some kind of termination element (a C-style string, for instance, uses the null character \0
to terminate strings).
I have built a program which demonstrates all of this:
#include <iostream>
#include <typeinfo>
void func(int a[10], int b[]){
std::cout<<"a (inside function): "<<sizeof(a)<<"\n";
std::cout<<"b (inside function): "<<sizeof(b)<<"\n";
std::cout<<"a (inside function type): "<<typeid(a).name()<<std::endl;
std::cout<<"b (inside function type): "<<typeid(b).name()<<std::endl;
}
int main(){
int a[10];
int b[40];
std::cout<<"a (outside function): "<<sizeof(a)<<"\n";
std::cout<<"a (outside function type): "<<typeid(a).name()<<std::endl;
func(a,b);
}
The output is:
a (outside function): 40
a (outside function type): A10_i
a (inside function): 8
b (inside function): 8
a (inside function type): Pi
b (inside function type): Pi
Note that outside of the function, a
is an int array of length 10 (A10_i
) and the size is known. Inside the function, both a
and b
are pointers to ints (Pi
) and the total size of the arrays are unknown.