gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:06 24 4
gpt4 key购买 nike

我正在尝试使用 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;

}

没有我的编译器 (Visual C++) 告诉我 struct Employee* p = malloc(sizeof(struct Employee)); 类型“void *”不能转换为输入“员工 *”。我不知道这里出了什么问题。似乎 struct Employee 是空的,但我不明白为什么......

最佳答案

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

struct Employee* p = (struct Employee*) malloc(sizeof(struct Employee));

关于c++ - 使用 malloc() 和 sizeof() 在堆上创建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4519834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com