英文:
C - Array decays into pointers only when passed as arguments?
问题
"Array decays into pointers" only when they are passed as arguments into other functions or always when declared (except these cases)? So does this mean that if I do the same thing in a function that accepts an array, but in the main
function, the array won't decay into a pointer?
英文:
I read a lot of topics about C and decay of the arrays, but I don't understand a big thing yet. "Array decays into pointers" only when they are passed ad arguments into another functions or always when declared (except these cases)? So this mean, if I do the same stuff of a function which accepts an array, but in the main
, in this one the array won't decay into a pointer?
答案1
得分: 5
在表达式中使用数组时,除非:
- 它是
sizeof
的操作数, - 它是一元
&
(“地址”而不是二元“与”的)的操作数,或者 - 它是用于初始化数组的字符串文字(例如
char foo[] = "abc";
)。
当函数声明包含将参数声明为数组的声明时,这不是一个表达式。在分析声明时,没有数组,因此没有将数组转换为指针。但是,有一个声明的调整。当参数声明声明数组时,它会自动调整为声明指针。
有关在表达式中转换数组的规则,请参见C 2018 6.3.2.1 2。有关在参数声明中调整数组的规则,请参见6.7.6.3 7。
英文:
When an array is used in an expression, it is automatically converted to a pointer to its first element except when:
- it is the operand of
sizeof
, - it is the operand of unary
&
(“address of”, not the binary “AND”), or - it is a string literal used to initialize an array (as in
char foo[] = "abc";
).
When a function declaration includes a declaration of a parameter as an array, that is not an expression. There is no array when the declaration is analyzed, so there is no conversion of an array to a pointer. However, there is an adjustment of the declaration. When a parameter declaration declares an array, it is automatically adjusted to declare a pointer instead.
The rule for converting arrays in expressions is in C 2018 6.3.2.1 2. The rule for adjusting arrays in parameter declarations is in 6.7.6.3 7.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论