Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between a pointer parameter and an array parameter?

void method(double *v)

void method(double v[5])

Is there any difference between these two?

Is the second one more specific, as in v being constrained to 5 elements in length?

like image 668
Adam Lee Avatar asked Mar 16 '14 14:03

Adam Lee


2 Answers

Arrays when declared as parameter types, decay to the pointer types. In your example,

void method(double v[5]);

Here 5 doesn't play any role at all, it is so insignificant that you may omit it altogether, and write this instead:

void method(double v[]);

which is exactly same as the previous declaration. Since it decays into pointer, so the above two are exactly same as:

void method(double *v); //because array decays to pointer, anyway

That is, all the following are declarations of the same function:

void method(double v[5]); //ok : declaration 
void method(double v[]);  //ok : redeclaration of the above
void method(double *v);   //ok : redeclaration of the above

ALL are exactly same. No difference at all.

Note that the following is different however:

void f(double (&v)[5]); 

It declares a function which can take array of doubles of size exactly 5. If you pass array of any other size (or if you pass pointers), it will give compilation error!

like image 112
Nawaz Avatar answered Sep 22 '22 10:09

Nawaz


No and no.

When in function arguments, they are the same, the compiler treats the argument double v[5] as a pointer. The size 5 is ignored, it's at most a signal for the programmer.

C++ 11 §8.3.5 Functions Section 3

[ ... ] After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively.

like image 37
Yu Hao Avatar answered Sep 22 '22 10:09

Yu Hao