malloc()
函数形成一个单独的内存块(比如 20 个字节类型转换为 int
),那么如何将它用作 int 的数组
block 就像 calloc()
函数一样?它不应该用于在整个 20 个字节(20*8 位)中只存储一个 int
值吗?
最佳答案
(say 20 bytes typecasted to int)
不,返回的内存作为指向 void
的指针给出,这是一个不完整的类型。
我们将返回的指针赋给某个类型的指针变量,我们可以使用该变量来访问内存。
引用 C11
,章节 §7.22.3,内存管理函数
[....] The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). [...] The pointer returned points to the start (lowest byte address) of the allocated space. [....]
由于分配的内存是连续的,因此指针算法可以工作,就像在数组的情况下一样,因为在数组中,元素也被放置在连续的内存中。
关于c - malloc函数内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56443825/