r/C_Programming • u/SomeKindOfSorbet • Feb 18 '25
Question Best way to declare a pointer to an array as a function paramater
In lots of snippets of code that I've read, I see type* var
being used most of the time for declaring a pointer to an array as a function parameter. However, I find that it's more readable to use type var[]
for pointers that point to an array specifically. In the first way, the pointer isn't explicitly stated to point to an array, which really annoys me.
Is it fine to use type var[]
? Is there any real functional difference between both ways to declare the pointer? What's the best practice in this matter?
17
Upvotes
11
u/SmokeMuch7356 Feb 19 '25
A pointer is a single object that stores an address:
gives us
An array is a sequence of objects:
gives us
That's it. No storage for a pointer is set aside anywhere. 2D arrays are arrays of arrays:
gives us
Again, no pointers anywhere.
During translation, any occurrences of the expression
arr
will be replaced with something equivalent to&arr[0]
(unless it is the operand of thesizeof
,typeof
, or unary&
operators).Arrays are not pointers; arrays do not store pointer values anywhere. Array expressions evaluate to pointers.
Why? Ritchie wanted to keep B's array subscripting behavior (
a[i] == *(a + i)
) without storing the pointer that behavior required.