考虑以下 C 代码片段:
int main() {
int *crr;
int arr[] = {1, 2, 3, 45};
crr = (int *)malloc(sizeof arr);
printf("%ld\n", sizeof arr);
printf("%ld", sizeof crr);
return 0;
}
上述代码的输出是:
16
8
我有 64 位架构系统。因此,int 是 4 个字节。需要解释或任何引用来解释为什么会发生这种情况。我已为 crr
分配了相同数量的内存.
最佳答案
sizeof arr
计算结果为 arr
的大小(以字节为单位)。因为arr
是一个由四个四字节int
组成的数组,所以它的大小是16字节。
sizeof crr
计算结果为 crr
的大小。因为crr
是一个八字节指针,所以它的大小是八个字节。
您可能已经习惯了数组通常会自动转换为指针的事实。当数组传递给函数时,它会转换为指针。当数组用在索引表达式中时,例如arr[2],它会被转换为指针(然后用指针算术将索引添加到它上面,并取消引用结果指针,就好像它被写成*(arr+2)
)。 sizeof
不会发生这种自动转换。 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…
关于c - 为什么在 C 中为数组声明动态分配的内存和指向数组声明的指针不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69282881/