Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Malloc,sizeof(int)*numRows和sizeof(int*[numRows]之间的差异_C_Malloc_Dynamic Memory Allocation - Fatal编程技术网

使用Malloc,sizeof(int)*numRows和sizeof(int*[numRows]之间的差异

使用Malloc,sizeof(int)*numRows和sizeof(int*[numRows]之间的差异,c,malloc,dynamic-memory-allocation,C,Malloc,Dynamic Memory Allocation,相当简单的内存分配,但我无法集中精力 以下两者之间的区别是什么: int **ans = (int**)malloc(sizeof(int*[numRows])); 及 我使用第二个版本得到堆缓冲区溢出,但是这里的实际区别是什么? 我尝试分配x个内存块类型int。 区别在于 大小(整数)*numRows vs sizeof(整数*[numRows]) 在第一种情况下 int **ans = (int**)malloc(sizeof(int*[numRows])); 为int*类型的numRo

相当简单的内存分配,但我无法集中精力


以下两者之间的区别是什么:

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

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

大小(整数)*numRows

vs

sizeof(整数*[numRows])

在第一种情况下

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*[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])
给出了10个元素的
int*
数组的大小,即80
sizeof(int)*numRows提供了10个
int
对象的大小,即40

编写
malloc
调用的更简洁、更不容易出错的方法是

int **ans = malloc( sizeof *ans * numRows );
由于
ans
具有类型
int**
,表达式
*ans
具有类型
int*
,因此
sizeof*ans
sizeof(int*)
相同。因此,我们分配了足够的空间来容纳
numRows
int*
实例

请记住,
sizeof
是一个运算符,而不是一个函数-语法是

sizeof ( type-name ) |
sizeof expression
将被解析为

(sizeof *ans) * numRows

演员阵容
(int**)
是不必要的。
sizeof(int)*numRows)
的大小为
numRow
int
s
sizeof(int*[numRows])
是指向
int
的指针数组的大小。完全不同的事情是的,我就是这么想的。这两条语句不相等。您试图分配一个指针数组,因此基本类型是
int*
not
int
。因此,第二个应该是
sizeof(int*)*numRows
。为了避免这种情况,可以这样做:
int**ans=malloc(sizeof(*ans)*numRows)?int*和int之间有什么区别?@Metio_1993 int*是指向int类型对象的指针类型。int是整数对象。@Metio_1993例如,在一般情况下,sizeof(int*)可以不等于sizeof(int)
sizeof *ans * numRows
(sizeof *ans) * numRows