-->
Page 1 of 2

How to pass an array to a function

PostPosted: Tue Feb 25, 2020 12:44 pm
by viktak
Hi All,
I have a function like this:

Code: Select allvoid myFunction(uint16_t buf[]) {
uint16_t size = sizeof(buf)
}



However, the size that gets calculated is wrong, shows 4 instead of the correct value (which is around 100).

When I use the the same line
Code: Select alluint16_t size = sizeof(myArray)
in the application, it works fine. So I guess I don't call the function correctly.

Could someone with more experience in c help me out?

Thanks in advance!

v

Re: How to pass an array to a function

PostPosted: Tue Feb 25, 2020 2:17 pm
by quackmore
you are doing everything right

the point is that when you pass an array argument to a function
you pass it by reference (the only way)
so "uint16_t buf[]" is not an array but a pointer
hence sizeof give you 4, the size of a pointer

you could change your function prototype as

Code: Select allvoid myFunction(uint16_t buf[], uint16_t size);


and then call it like this

Code: Select allmyFunction(myArray, sizeof(myArray));

Re: How to pass an array to a function

PostPosted: Wed Feb 26, 2020 3:44 am
by viktak
Thanks for the clarification! I suspected it was gonna be something along these lines, and in the meantime I did exactly what you proposed.

Can you confirm there is no way to send an argument by value in c++?

thanks!!

Re: How to pass an array to a function

PostPosted: Wed Feb 26, 2020 4:22 am
by quackmore
Code: Select allvoid myFunction(int *buf);
void myFunction(int buf[]);
void myFunction(int buf[10]);


whatever notation you will choose it will be always a call by reference
you can easily double check with sizeof...
and don't forget sizeof will give you the size of the array in bytes, not elements