在C中传递数组:方括号与指针 [英] Passing arrays in C: square brackets vs. pointer

查看:41
本文介绍了在C中传递数组:方括号与指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数组传递给函数.从我所看到的,有两种方法可以做到这一点:

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
}

每个呼叫者是:

int array[] = {0, 1, 2, 3, 4, 5};
f (array);

这两种方法之间有什么实际区别吗?

Is there any actual difference between these 2 approaches?

推荐答案

在您的特定示例中没有区别.

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

此规则的特定副作用是您可以将 void * 参数声明为 void [] 参数.

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

这篇关于在C中传递数组:方括号与指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆