C动态内存分配和sizeof() [英] C dynamic memory allocation and sizeof()
问题描述
我在理解这两个代码段之间的区别时遇到了一些麻烦: 我使用以下语句在代码内为整数数组动态分配空间
I'm having some trouble understanding the difference between these two code segments: I allocate space for an array of integers dynamically within my code with the following statement
int *arr = calloc(cnt, sizeof(int));
在另一个函数中,我要传入arr,我想确定arr的大小(元素数). 当我打电话
In another function, where I pass in arr, I would like to determine the size (number of elements) in arr. When I call
int arr_sz = sizeof(arr)/sizeof(int);
它仅返回1,这只是我假设的两个参数(4/4)= 1的int中的字节数. 我只是假设这与使用数组相同
it only returns 1, which is just the number of bytes in an int for both arguments I am assuming (4/4)=1. I just assumed it would be the same as using an array
int arr[8];
int arr_sz = sizeof(arr)/sizeof(int);
返回数组中元素的实际数量.
which returns the actual number of elements in the array.
如果有人可以解决这个问题,那就太好了.谢谢!
If anyone could clear this up, that would be great. Thanks!
推荐答案
int *arr; ----> Pointer
int arr[8]; ----> Array
首先要了解的内容-int *arr
是一个指针,指向某些字节的内存位置,不是一个数组.
First up what you got there - int *arr
is a pointer, pointing to some bytes of memory location, not an array.
数组和指针的类型不相同.
The type of an Array and a Pointer is not the same.
在传递arr的另一个函数中,我想确定arr的大小(元素个数).当我打电话
int arr_sz = sizeof(arr)/sizeof(int);
它仅返回1,这只是我假设的两个参数(4/4)= 1的int中的字节数.我只是认为这与使用数组相同
即使假定是成为一个数组,这也是因为数组在传递给函数时会衰减为指针.您需要在函数中显式传递数组大小作为单独的参数.
Even if it is assumed to be an Array -- that's because Arrays get decayed into pointers when passed into functions. You need to explicitly pass the array size in functions as a separate argument.
经历一下:
static
数组与动态内存分配之间存在差异.
There is a difference between a static
array and dynamic memory allocation.
sizeof运算符不适用于动态分配. AFAIK最适合与基于堆栈的类型和预定义类型一起使用.
The sizeof operator will not work on dynamic allocations. AFAIK it works best with stack-based and predefined types.
这篇关于C动态内存分配和sizeof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!