Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pointer or array in function parameters [duplicate]

is 1) float scalar_product(float *x, float *y) the same as 2) float scalar_product(float x[], float y[])?

I got some float a[3], b[3]; which contains some vectors and the function should give me the scalar product.

With my java background I wrote the 2) function (on paper) but the sample solution used the 1) with pointer's.

So my questions: Are they the same? If not, whats the difference and when should I use which?

like image 220
koin Avatar asked May 29 '26 04:05

koin


1 Answers

Yes, both the versions are effectively same, because, when arrays are passed as function arguments, they essentially decay to the pointer to the first element.

So, making the function parameter as pointer or array will have no behavioral change.

Related, C11, chapter §6.7.6.3, Function declarators

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’ [...]

So, float scalar_product(float x[], float y[]) ends up being the same as float scalar_product(float *x, float *y).

like image 94
Sourav Ghosh Avatar answered May 31 '26 11:05

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!