I'm wanting to pass an array into a function. From what I can see, there are 2 ways of doing this:
1.
void f (int array[]) {
// Taking an array with square brackets
}
2.
void f (int *array) {
// Taking a pointer
}
Each one is called by:
int array[] = {0, 1, 2, 3, 4, 5};
f (array);
Is there any actual difference between these 2 approaches?
An array is a pointer. An array is considered to be the same thing as a pointer to the first item in the array. That rule has several consequences.
An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.
The main difference between Array and Pointers is the fixed size of the memory block. When Arrays are created the fixed size of the memory block is allocated. But with Pointers the memory is dynamically allocated.
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.
In your specific example there is no difference.
In more general case one difference between these two approaches stems from the fact that in case of []
syntax the language performs "usual" checks for correctness of array declaration. For example, when the []
syntax is used, the array element type must be complete. There's no such requirement for pointer syntax
struct S;
void foo(struct S *a); // OK
void bar(struct S a[]); // ERROR
A specific side-effect of this rule is that you cannot declare void *
parameters as void []
parameters.
And if you specify array size, it has to be positive (even though it is ignored afterwards).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With