关于 C 中 malloc 和 calloc 函数的混淆

Confusion about malloc and calloc function in C

malloc 函数的声明:

void *malloc(size_t size);

这里,malloc returns 空指针。所以,一个 void 函数 return 什么都没有,然后

为什么要给指针赋值malloc(函数调用)?

例如:

int *ptr;
ptr = malloc(10 * sizeof (*ptr));
^^^

return 值从 malloc() 得到什么???

对于语言设计者而言,这可能是一个不幸的选择,但他们决定为他们的 void* 结构重用 void,这几乎颠倒了它的意思:而 void 意味着"returns nothing"、void*表示"return a pointer to anything."

本质上,void*是一个指向未指定对象的指针。在取消引用之前,它必须转换为指向特定类型的指针。这正是 malloccalloc.

返回的那种指针

void 和 void* 是不同的。 void 意味着什么都没有,但 void* 可以是任何东西。 void (void*) 指针可以转换为任何其他指针。

为什么使用 malloc() return void*?

这意味着malloc为你分配了一个内存缓冲区,你可以用它来存储你想要的任何东西。

尽量不要被白色混淆 space。在 C 中,您应该这样阅读声明:

int *i; 被读作 - 变量 *i 给出一个 int 变量 i 这是一个指针一个整数。功能也是如此。像 void *fun() 这样的东西意味着 fun 是一个 returns 指向 void 的函数。检查 this 以获得更完整的答案。