Domanda

According to "Difference between passing array and array pointer into function in C", there's no semantic difference between these two ways of declaring parameters since "array parameters [are being] treated as though they were declared as pointers".

void f1(int a[]) { /* ... */ }
void f2(int* a)  { /* ... */ }

There is, however, a big difference between dealing with arrays and pointers. One could, for example, find out the size of an array using sizeof(some_array). When dealing with a pointer, though, this is just going to reveal the size of the pointer itself. (Sidenote: This is a pretty neat workaround concerning that issue.)

This is why I find it to be misleading to declare parameters like that: f1(int a[]). As djechlin pointed out in "Difference between array and pointer as a function's argument in c", I think it can trick one into thinking that one is actually dealing with arrays instead of just pointers: "Therefore I always prefer the pointer form, as the array form can cause subtle confusion."

That being said, I wonder why people keep using the "array form" as there seems to be no reason to do so. What am I missing here? In his book Learn C The Hard Way, Zed Shaw actually mixes both ways:

void print_arguments(int argc, char *argv[]) { /* ... */ }

They also do it in K&R2.

Why? I am familiar with the reasons for not doing it, but what are the pros?

È stato utile?

Soluzione 2

Which one is easier to understand:

char *argv[] is intended to be an array of pointers to chars

or

char **argv is a pointer to a pointer to a char

Yes, you can code C in a non-intuitive way, but why would you?

Which do you prefer:

a[2]
*(a + 2)
*(2 + a)
2[a]

all have the same effect. Why use [] when it is just syntactic sugar? Because it is more readable. In a similar vein: (*ps).member is not as readable as ps->member

Altri suggerimenti

Technically, I'm unaware of any reason, but semantically the meaning is a lot clearer.

If I see a function take a pointer to something, I would expect it to be a single item unless the variable name (and/or possibly function name) makes it clear that it will be anticipating an array.

Whereas if it is labelled as taking an array, that is quite obvious. This is especially the case with multiple ** - take the char *argv[] example. That is clearly a pointer to an array of char*'s (i.e. strings). char **argv could be that, but it could also be a mutable pointer (e.g. for freeing). While char argv[][] would imply a two dimensional array (something char *argv[] does not).

Although both declaration are same , first one is preferable when you want to pass a pointer to an array. One can easily understand that.
In case of latter, it is not predictable that whether you are passing a pointer to a single element or an array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top