为什么没有铸造malloc不工作?

thk*_*ang 1 c malloc

请考虑以下代码:

#include "stdafx.h"
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

struct Person *Person_create(char *name, int age, int height, int weight)
{
    struct Person *who = (struct Person*) malloc(sizeof(struct Person));
    assert(who != NULL);

    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是

struct Person *who = (struct Person*) malloc(sizeof(struct Person));
Run Code Online (Sandbox Code Playgroud)

我在网上搜索了一下malloc()用法.大约一半是用铸造写的,有些则不是.在vs2010上,没有(struct Person*)出现错误出现:

1>c:\users\juhyunlove\documents\visual studio 2010\projects\learnc\struct\struct\struct.cpp(19): error C2440: 'initializing' : cannot convert from 'void *' to 'Person *'
1>          Conversion from 'void*' to pointer to non-'void' requires an explicit cast
Run Code Online (Sandbox Code Playgroud)

那么创建指针并为其分配内存的正确方法是什么?

oua*_*uah 14

因为您使用的是C++编译器.

在C++中需要强制转换malloc(假设类型不是void *).在C中,它不是必需的,甚至建议不要施放malloc.

在C中,void *在赋值期间存在从所有对象指针类型的隐式转换.

void *p = NULL;
int *q = p;  // valid in C, invalid in C++
Run Code Online (Sandbox Code Playgroud)