假设我声明一个将数组作为指针传递的函数:
void fun(int *A, int n);
如果我改用特定于数组的指针,即
void fun(int A[], int n);
它有什么特别的优势吗?
最佳答案
(这个答案是针对 C 的。)
对于大小为 []
的 int
数组,编译器没有区别,因为 C 2018 6.7.6.3 7 说:
A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the
[
and]
of the array type derivation…
但是,对于某些类型T
,一般来说,是有区别的。 Per C 2018 6.7.6.2 1,在数组的声明中,元素类型必须是完整的,即使稍后数组将调整为指针:
… The element type shall not be an incomplete or function type…
考虑 typedef int T[];
,它将 T
定义为 int []
的别名,int []
是 int
具有未知数量的元素。此类型不完整,因为元素数量未知。所以我们不能声明一个T
的数组。相反,指针可能指向不完整的类型。所以 void fun(T *A, int n);
是允许的,但是 void fun(T A[], int n);
是不允许的,因为它违反了 6.7.6.2 1.
另一个区别是大小是否指定并且是可变的。然后可以在调用函数时对其进行评估。 (C 标准对此没有明确说明,但 Clang 和 GCC 对其进行了评估。)例如,给定一个函数定义 void fun(int A[printf("Hello, world.\n")], int n) { … }
,当调用 fun
时,“Hello, world”。将被打印。这当然不会发生在 void fun(int *A, int n) { … }
中。
关于arrays - 将数组作为 int A[] 而不是 int *A 传递有什么优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67357997/