3

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
koin
  • 203
  • 2
  • 12
  • When to use what is pretty much a matter of readability. If you want to distinguish between what kind of data is being passed, then by all means use the second method signature. But for all intents and purposes, they're the same. – cs95 Jul 03 '16 at 20:47
  • This must be a duplicate. – alk Jul 03 '16 at 20:49
  • Here we are: http://stackoverflow.com/q/16258075/694576 – alk Jul 03 '16 at 20:52
  • 1
    it becomes more tricky when there are two or more dimensions to the array. – Weather Vane Jul 03 '16 at 20:52
  • 1
    And here: http://stackoverflow.com/q/16144535/694576 and here: http://stackoverflow.com/q/15261509/694576 – alk Jul 03 '16 at 20:54

1 Answers1

2

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).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261