[SOLVED] Passing arrays in C: square brackets vs. pointer

Issue

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?

Solution

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

Answered By – AnT

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.