im trying to get the sizeof char array variable in a different function where it was initialize however cant get the right sizeof. please see code below
int foo(uint8 *buffer){
cout <<"sizeof: "<< sizeof(buffer) <<endl;
}
int main()
{
uint8 txbuffer[13]={0};
uint8 uibuffer[4] = "abc";
uint8 rxbuffer[4] = "def";
uint8 l[2]="g";
int index = 1;
foo(txbuffer);
cout <<"sizeof after foo(): " <<sizeof(txbuffer) <<endl;
return 0;
}
the output is:
sizeof: 4
sizeof after foo(): 13
desired output is:
sizeof: 13
sizeof after foo(): 13
This can't be done with pointers alone. Pointers contain no information about the size of the array - they are only a memory address. Because arrays decay to pointers when passed to a function, you lose the size of the array.
One way however is to use templates:
template <typename T, size_t N>
size_t foo(const T (&buffer)[N])
{
cout << "size: " << N << endl;
return N;
}
You can then call the function like this (just like any other function):
int main()
{
char a[42];
int b[100];
short c[77];
foo(a);
foo(b);
foo(c);
}
Output:
size: 42
size: 100
size: 77
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With