使用malloc()和sizeof()在堆上创建结构

Ord*_*rdo 4 c++

我正在尝试使用malloc()和sizeof()在堆上创建一个结构.这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Employee
{
    char first[21];
    char last[21];
    char title[21];
    int salary;
};


struct Employee* createEmployee(char* first, char* last, char* title, int salary) // Creates a struct Employee object on the heap.
{
    struct Employee* p = malloc(sizeof(struct Employee)); 

    if (p != NULL)
    {
        strcpy(p->first, first);
        strcpy(p->last, last);
        strcpy(p->title, title);
        p->salary, salary;
    }
    return p;

}
Run Code Online (Sandbox Code Playgroud)

没有我的编译器(Visual C++)告诉我该行struct Employee* p = malloc(sizeof(struct Employee));"void*"无法转换为"Employee*"类型.我不知道这里有什么问题.似乎struct Employee是一个空白,但我不明白为什么......

use*_*379 13

在C++中(因为您使用Visual C++进行编译),您必须显式地转换返回的指针malloc:

struct Employee* p = (struct Employee*) malloc(sizeof(struct Employee));
Run Code Online (Sandbox Code Playgroud)


R..*_*R.. 11

使用的最佳做法malloc:

struct Employee *p = malloc(sizeof *p); 
Run Code Online (Sandbox Code Playgroud)

您还需要修复您的IDE /编译器,告诉它您正在编写C而不是C++,因为它太过于破碎而无法自行解决这个问题......

由于有些人似乎对这个答案不满意(并且我不同意其他答案),我想我应该解释为什么解决这个问题并不好.

在C中,转换malloc的返回值是有害的,因为如果您忘记包含stdlib.h或其他原型malloc,它会隐藏警告.它还使您的代码难以维护; 如果需要更改p的类型,那么演员的所有答案都需要进行3次更改,而我的答案只需要在一个地方进行更改.最后,新的C程序员在看到编译器警告或错误时不应该养成使用强制转换的坏习惯.这通常只会掩盖错误.正确的代码几乎从不需要强制转换,它们的使用应被视为代码气味

  • 很好.我已经在问题中修复了标记,但我仍然认为接受的答案是错误的建议.如果你正在编写C++,你应该使用`new`,而不是`malloc`.如果你正在写C,那么你永远不应该写这样的演员表. (3认同)
  • 当所有现有的答案都是同一件事的重复,并且所有人都忽略了OP的真正问题(编译为错误的语言)并给出了一个丑陋的解决方法时,还有什么比将它们全部贬低更好?只是低估第一个?关注我自己的事业? (2认同)