Is there any advantage to passing a pointer to an array to a function?

Viewed 99

I originally thought that the key advantage to passing a pointer to an array to a function was to prevent copying of the entire array. However the answer to , this question points out that even if the function's parameter is int [] it decays into a pointer. I wrote sample code and verified this myself.

I have done googling and reading and mostly what I see is that historically there was some advantage to using pointers which avoided extra arithmetic calculations array indexing requires. But the articles also said that today this is no longer an issue because compilers and chip makers have made aggressive optimizations and array indexing is just as fast.

If this is true, is there any practical advantage to passing the pointer explicitly?

I don't know if this question will elicit opinion based responses. If so, it is not my intention. I am hoping for a response that makes a clear case for explicitly passing pointers. Thanks.

Edit Links to articles I read:

How come my array index is faster than pointer

http://www.c-faq.com/aryptr/aryptrequiv.html

2 Answers

Passing int * and int [] are identical; the latter is just an alternate syntax. However, passing int (*)[N] (a pointer-to-array type rather than just a pointer to its first element) is not the same. In the case of

void foo(int (*p)[N]);
int array[N];
foo(&array);

there's no mechanical difference in how it's passed; the difference is just the type, and therefore the need to write an additional * in the callee ((*p)[i] instead of p[i]).

However passing pointer-to-array types makes a lot of sense as soon as you have multi-dimensional arrays, as in:

void foo(int (*p)[N]);
int array[M][N];
foo(array);

Here there is no & before array, because it decays to a pointer to its first element (the first one-dimensional int [N] "row") yielding a pointer-to-array type. Then the callee is able to accesss the 2D array as p[i][j].

With arrays you can require a size which it must have at least; e.g.

extern void foo(uint8_t mac_address[static 6]);

void bar(void) {
    uint8_t mac[4];
    foo(mac);
}

can cause to emit some diagnostics.

Else they behave identically. Arrays might be used e.g. for documentation purposes.

Related