C – 仅当作为参数传递时,数组会转化为指针。

huangapple go评论68阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月23日 23:21:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定