I understand how arrays decay to pointers. I understand that, for the compiler, this:
void foo(int *arg1);
is 100% equivalent to this:
void foo(int arg1[]);
Should one style be preferred over the other? I want to be consistent, but I'm having a hard time justifying either decision.
Although int main(int argc, char *argv[])
and int main(int argc, char **argv)
are the same, the former seems to be much more common (correct me if I'm wrong).
Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.
An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
Similarly, you can pass multi-dimensional arrays as formal parameters.
2.4: Then why are array and pointer declarations interchangeable as function formal parameters? Since arrays decay immediately into pointers, an array is never actually passed to a function. As a convenience, any parameter declarations which "look like" arrays, e.g. f(a) char a[];
I would recommend against using the []
syntax for function parameters.
The one argument in favour of using []
is that it implies, in a self-documenting way, that the pointer is expected to point to more than one thing. For example:
void swap(int *x, int *y)
double average(int vals[], int n)
But then why is char *
always used for strings rather than char []
? I'd rather be consistent and always use *
.
Some people like to const
everything they possibly can, including pass-by-value parameters. The syntax for that when using []
(available only in C99) is less intuitive and probably less well-known:
const char *const *const words
vs. const char *const words[const]
Although I do consider that final const
to be overkill, in any case.
Furthermore, the way that arrays decay is not completely intuitive. In particular, it is not applied recursively (char words[][]
doesn't work). Especially when you start throwing in more indirection, the []
syntax just causes confusion. IMO it is better to always use pointer syntax rather than pretending that an array is passed as an argument.
More information: http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=aryptr#aryptrparam.
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