c - 为什么在 C 中为数组声明动态分配的内存和指向数组声明的指针不一样?

标签 c malloc dynamic-memory-allocation

考虑以下 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/

相关文章:

无法在 netbeans 中运行我的 C 代码

c - 我的链接器会链接不需要的源文件中的对象吗?

c - 当我使用malloc时,如何在C中获取* char的大小?

c - malloc 位字段值到 c 中的数组

CUDA新建删除

c - 在 C 中为队列的前面元素分配内存时出现段错误

c - 程序可以编译,但在提供输入时不执行任何操作

c++ - C 中的逻辑运算符和位操作

c - 在尝试释放()之前确定结构成员是否具有有效数据

c++ - 返回的对象是临时的还是匿名的,是否会导致内存泄漏?