malloc() 总是 return 字符指针吗?

Does malloc() always return a character pointer?

我有一本书是这样说的:

The malloc() allocation still has one slight problem. We still have to explain the left portion of the temperature malloc(). What is the (int *) for?

The (int *) is a typecast. You’ve seen other kinds of typecasts in this book. To convert a float >value to an int, you place (int) before the floating-point value, like this:

aVal = (int)salary;

The * inside a typecast means that the typecast is a pointer typecast. malloc() always returns a character pointer. If you want to use malloc() to allocate integers, floating points, or any kind of data other than char, you have to typecast the malloc() so that the pointer variable that receives the allocation (such as temps) receives the correct pointer data type. temps is an integer pointer; you should not assign temps to malloc()’s allocated memory unless you typecast malloc() into an integer pointer. Therefore, the left side of the previous malloc() simply tells malloc() that an integer pointer, not the default character pointer, will point to the first of the allocated values.

温度:

int * temps; /* Will point to the first heap value */
temps = (int *) malloc(10 * sizeof(int)); /* Yikes! */

看了类似的帖子后,据说malloc() returns 是void 类型的指针,不是character 类型的指针。我错过了什么吗?我知道在 C.

中不需要类型转换 malloc()

正如评论中提到的 user207421,您的书很可能已经很旧了。最初,C 没有通用指针类型(即 void*)。我忘了这是什么时候添加的。当时最接近的是 char* 因为每个指针,无论其类型如何,都可以安全地转换为 char* (有点)。

在 1989 标准之前,C 没有“通用”指针类型;指针类型不兼容,因此要将 char * 值分配给 int * 变量(反之亦然),您需要将该值显式转换为目标类型。

同样在 1989 标准之前,所有内存分配函数 (malloc/calloc/realloc) returned char *,所以如果你将结果分配给不同的指针类型,你有使用强制转换:

int *ptr = (int *) malloc( some_size );

坦率地说,这让人很头疼。人们认识到 C 可以使用某种“通用”指针类型,因此引入了 void * 类型,以及 void * 值可以转换为其他指针类型的规则(反之亦然) ) 无需演员表。内存分配函数已更改为 return void *,因此不再需要强制转换:

int *ptr = malloc( some_size );

您不能取消引用 void * - 结果将是 void 类型,它没有值也没有大小。出于同样的原因,您不能在 void *.

上进行指针运算或使用下标运算符

Does malloc() always return a character pointer?

没有。从 C89 开始,malloc() returns 一个 void *.