arrays - 将数组作为 int A[] 而不是 int *A 传递有什么优势吗?

标签 arrays c function pointers

假设我声明一个将数组作为指针传递的函数:

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/

相关文章:

c - 将随机数分配给二维数组时,嵌套 For 循环永远不会结束。

c - 如果一个点位于对数螺线附近 : Not returning points near the center

c - 调用 FreeImage_GetPixelColor() 时出现奇怪的段错误

javascript - javascript中的函数未定义

php - 这个php代码有什么问题?

c - 带指针的多维数组中的数组大小

python - 必须以实例作为第一个参数调用未绑定(bind)方法 - python

c++ - 将 R 函数作为参数传递给 RCpp 函数

JAVA从文件中填充未知行数的二维数组

sql - 获取 oracle.sql.array 的长度