Why are arrays considered as pointers in function arguments of a function in C++ . Here, I have a few snippets of Code to illustrate my concern:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
void test(uint32_t x[3])
{
cout << "Inside test : "<< sizeof(x) << endl;
}
int main()
{
uint32_t n[3];
cout << "Size of array in bytes : " << sizeof(n) << endl;
test(n);
return 0;
}
This is the output that I get:
Size of array in bytes : 12
Inside test : 4
In the first case I get the actual size of the array , but when test() is called the output is 4 bytes which is same as sizeof(uint32_t *) .
What is the reason for this behaviour ?
Every help is appreciated!
sizeof(uint32_t) * 3for calculating the size of my array ?std::array(by pointer or reference) if you have a fixed size. That case there's no decaying to worry aboutuint32_t (*x)[3](the address of an array of three elements) which means the call inmain()needs to pass&n, and*x(or(*x)) inside the function is the array with three elements. In C++ (not C) it is possible to pass `uint32_t (&x)[3](reference to an array of three elements). HOWEVER, in both cases, the length of the array is fixed (a compile time constant), so it is not possible to pass an array with 4 elements to a function that expects a pointer/reference to an array with three elements.