c - malloc函数内存管理

标签 c malloc dynamic-memory-allocation

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. [....]

由于分配的内存是连续的,因此指针算法可以工作,就像在数组的情况下一样,因为在数组中,元素也被放置在连续的内存中。

澄清一点,a pointer is not an array.

关于c - malloc函数内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56443825/

相关文章:

c - 在 C 中使用任意大小的 uint8_t 数组生成所有可能的二进制组合

c - 在 Solaris 中的父进程和子进程之间共享内存(在 C 中)

c - 为什么当我什么都不输入时程序会打印出 "@"?

c - 使用 memcpy 获取段错误

c - 在不同级别的函数中传递参数

c - 在不使用 malloc() 的情况下,下面的程序如何工作?

c - 如何在 C 中为以下代码调试段错误。我在许多函数以及 main 中使用了 malloc 和 free

c - C 中二维字符矩阵的动态内存分配

c - 结构体数组的动态内存分配。计划结束 [C]

c - 增加在数组指针数组中实现的数组的最后一行?