I am a little bit confused about pass an array in C/C++. I saw some cases in which the signature is like this
void f(int arr[])
some is like this
void f(int arr[], int size)
Could anybody elaborate what’s the difference and when and how to use it?
First, an array passed to a function actually passes a pointer to the first element of the array, e.g., if you have
Then,
f()gets&a[0]passed to it. So, when writing your function prototypes, the following are equivalent:This means that the size of the array is lost, and
f(), in general, can’t determine the size. (This is the reason I prefervoid f(int *arr)form overvoid f(int arr[]).)There are two cases where
f()doesn’t need the information, and in those two cases, it is OK to not have an extra parameter to it.First, there is some special, agreed value in
arrthat both the caller andf()take to mean “the end”. For example, one can agree that a value0means “Done”.Then one could write:
and define
f()something like:Obviously, the above scheme works only if both the caller and the callee agree to a convention, and follow it. An example is
strlen()function in the C library. It calculates the length of a string by finding a0. If you pass it something that doesn’t have a0at the end, all bets are off, and you are in the undefined behavior territory.The second case is when you don’t really have an array. In this case,
f()takes a pointer to an object (intin your example). So:with
is fine:
f()is not operating on an array anyway.