传递数组名称时 sizeof 如何工作
how a sizeof works when array name is passed
为什么 sizeof(array_name) 是数组的大小,而 sizeof(&a[0]) 是指针的大小,即使将数组名传递给函数时,传递的是数组开始的位置。
在大多数表达式中,当使用数组时,它会自动转换为指向其第一个元素的指针。
sizeof
有一个特殊的规则:当数组是sizeof
的操作数时,它不会自动转换为指针。因此,sizeof array_name
给出的是数组的大小,而不是指针的大小。
此规则也适用于一元&
运算符:&array_name
是数组的地址,不是指针的地址。
此外,如果数组是用于初始化数组的字符串文字,则不会将其转换为指针。字符串文字用于初始化数组。
规则是 C 2018 6.3.2.1 3:
Except when it is the operand of the sizeof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
函数的数组参数不存在。它们变成指针(如果数组是多维的,最里面的索引就是)。它只是继承自B语言的语法糖。 void f(int *X) == void f(int X[]);
(函数参数与函数相同。void g(void X(void)) == void g(void (*X)(void))
)。
为什么 sizeof(array_name) 是数组的大小,而 sizeof(&a[0]) 是指针的大小,即使将数组名传递给函数时,传递的是数组开始的位置。
在大多数表达式中,当使用数组时,它会自动转换为指向其第一个元素的指针。
sizeof
有一个特殊的规则:当数组是sizeof
的操作数时,它不会自动转换为指针。因此,sizeof array_name
给出的是数组的大小,而不是指针的大小。
此规则也适用于一元&
运算符:&array_name
是数组的地址,不是指针的地址。
此外,如果数组是用于初始化数组的字符串文字,则不会将其转换为指针。字符串文字用于初始化数组。
规则是 C 2018 6.3.2.1 3:
Except when it is the operand of the sizeof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
函数的数组参数不存在。它们变成指针(如果数组是多维的,最里面的索引就是)。它只是继承自B语言的语法糖。 void f(int *X) == void f(int X[]);
(函数参数与函数相同。void g(void X(void)) == void g(void (*X)(void))
)。