【问题标题】:Using Malloc, Difference between sizeof(int) * numRows and sizeof(int * [numRows])使用 Malloc,sizeof(int) * numRows 和 sizeof(int * [numRows]) 之间的区别
【发布时间】:2021-06-09 20:51:54
【问题描述】:

相当简单的内存分配,但我无法理解。

有什么区别:

int **ans = (int**)malloc(sizeof(int*[numRows]));

int **ans = (int**)malloc(sizeof(int)*numRows); 

我使用第二个版本得到堆缓冲区溢出,但这里的实际区别是什么? 我尝试分配 x 数量的内存块类型 int。 区别是

sizeof(int) * numRows

sizeof(int * [numRows])

【问题讨论】:

  • 演员(int**) 是不必要的。
  • sizeof(int)*numRows) 的大小为 numRow ints。 sizeof(int*[numRows]) 是指向int 的指针数组的大小。完全不同的东西
  • 是的,我就是这么想的。这两个语句不等价。
  • 你试图分配一个指针数组,所以基本类型是int *而不是int。因此,第二个应该是sizeof(int *) * numRows
  • 为了避免这种情况,如何:int **ans = malloc(sizeof(*ans) * numRows);?

标签: c malloc dynamic-memory-allocation


【解决方案1】:

int * [numRows] 不是乘法表达式,它是一个类型 - 它是一个指向int 的指针数组。所以sizeof (int * [numRows])int * 数组的大小(以字节为单位),即numRows 元素宽。

sizeof (int) * numRows, OTOH 是一个乘法表达式 - 您将 int 的大小乘以行数。所以,让我们做一些假设:

numRows        == 10;
sizeof (int)   ==  4;  // common on most platforms
sizeof (int *) ==  8;  // common on most 64-bit platforms

所以,sizeof( int * [numRows]) 为我们提供了 int * 的 10 元素数组的大小,即 80。sizeof (int) * numRows 为我们提供了 10 个 int 对象的大小,即 40。

malloc 调用的编写方式更简洁且不易出错

int **ans = malloc( sizeof *ans * numRows );

由于ans 的类型为int **表达式 *ans 的类型为int *,因此sizeof *anssizeof (int *) 相同。所以我们分配了足够的空间来容纳numRowsint * 实例。

记住sizeof是一个操作符,而不是一个函数——语法是

sizeof ( type-name ) |
sizeof expression

是一元运算符,优先级高于乘法运算符,所以

sizeof *ans * numRows

将被解析为

(sizeof *ans) * numRows

【讨论】:

    【解决方案2】:

    第一种情况

    int **ans = (int**)malloc(sizeof(int*[numRows]));
    

    int * 类型的numRows 元素数组分配了内存。

    第二种情况

    int **ans = (int**)malloc(sizeof(int)*numRows); 
    

    int 类型的numRows 元素数组分配了内存,分配的内存被解释为int * 类型的元素数组,而不是int。因此,如果您假设内存存储具有int * 类型元素的数组,则可以调用未定义的行为,因为通常sizeof( int * ) 可能不等于sizeof( int )。但即使它们相等,这样的调用也只会让代码的读者感到困惑,并且会成为潜在的错误

    【讨论】:

    • int * 和 int 有什么区别?
    • @Metio_1993 int * 是指向 int 类型对象的指针类型。 int 是一个整数对象。
    • @Metio_1993 例如通常 sizeof( int * ) 可以不等于 sizeof( int )
    猜你喜欢
    • 2014-08-13
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多