Passing arrays in C: square brackets vs. pointer

独自空忆成欢 提交于 2021-02-04 17:14:26

问题


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?


回答1:


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 canon declare void * parameters as void [] parameters.

And if you specify array size, it has to be positive (even though it is ignored afterwards).




回答2:


There is no difference apart from the syntax. For historical reasons, even though int array[] looks like it should pass an array, it actually passes a pointer (meaning it's the same as int *array).

If I were you, I would prefer int *array just because it does what it looks like it does - that is, it's less likely to confuse you.




回答3:


They are identical, by definition. The calling code always passes an array argument as a pointer, even if it looks like the caller is passing an array. The array-like parameter declaration might make it look more like the call, but the pointer parameter declaration more accurately reflects what's actually going on.

See also this entry in the C FAQ list.

As Dennis Ritchie explains in "The Development of the C Language", the pointer declaration is actually a "living fossil", a relic from a very early version of C where arrays and pointers worked quite differently.



来源:https://stackoverflow.com/questions/44489773/passing-arrays-in-c-square-brackets-vs-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!