我很好奇 sizeof(arrayName + offset)
。它给了我 sizeof(pointer)
。尽管数组名在 C 中实际上是一个常量指针,sizeof(arrayName)
给出了数组的大小(以字节为单位)。所以我猜编译器将 (arrayName+offset)
视为纯指针,即使对于 sizeof()
也是如此,因此使用数组名称时唯一的异常(exception)是 sizeof(arrayName )
。
这种行为 sizeof(arrayName + offset)
是否由编译器明确定义?我正在使用 MinGW 32 位编译器。
除了使用像 (sizeof(arrayName) - offset*sizeof(arrayName[0]))
这样的简单数学之外,还有什么方法可以让我们知道部分数组的大小?
sizeof(arrayName)
不是 C/C++ 中不一致的语言构造吗?对于所有其他用途,arrayName
被视为地址。当我们将数组传递给函数时,这种行为可能会导致错误,初学者总是对此有疑问。
最佳答案
除了三种情况外,数组名称都被转换为指向其第一个元素的指针:
- 寻址运算符的操作数
&
sizeof
运算符的操作数。_Alignof
运算符的操作数。
这在 C standard 的第 6.3.2.1 节中有详细说明:
3 Except when it is the operand of the
sizeof
operator, the_Alignof
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.
在 sizeof(arrayName + offset)
的情况下,sizeof
的操作数是表达式 arrayName + offset
。此表达式的类型是指针类型,因为 arrayName
被转换为指针以便执行带有 offset
的指针运算。因此 sizeof
表达式的计算结果为指针的大小。
在 sizeof(arrayName)
的情况下,sizeof
的操作数是一个数组,因此它计算为数组的大小(以字节为单位)。
这两种行为都由 C 标准明确定义。
关于c - 添加偏移量时数组名称上的 sizeof 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49546763/