Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array syntax vs. pointer syntax in C function parameters

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

like image 690
mk12 Avatar asked Aug 26 '12 04:08

mk12


People also ask

What is the difference between pointer and array in C?

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.

What is the difference between array and pointer variable?

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.

Can an array be a parameter in C?

Similarly, you can pass multi-dimensional arrays as formal parameters.

Why are array and pointer declarations interchangeable as function 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[];


1 Answers

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.

like image 172
mk12 Avatar answered Sep 28 '22 14:09

mk12