Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays in C: square brackets vs. pointer

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?

like image 759
Luke Avatar asked Jun 11 '17 23:06

Luke


People also ask

Is array [] a pointer?

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.

Can you pass an array as a pointer in C?

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.

Which is better pointer or array?

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.

What's the difference between array and pointer in C?

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.


1 Answers

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).

like image 181
AnT Avatar answered Oct 19 '22 06:10

AnT