Monday, 8 August 2016

c++ - Using malloc() and sizeof() to create a struct on the heap



I'm trying to use malloc() and sizeof() to create a struct on the heap. Here is my code:



#include 

#include
#include

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;

}


No my compiler (Visual C++) tells me for the line struct Employee* p = malloc(sizeof(struct Employee)); that the type "void *" can't be converted to the type "Employee *". I don't know what is wrong here. Seems as if struct Employee is a void but i don't understand why...


Answer




In C++ (since you are using Visual C++ to compile), you have to explicitly cast the pointer returned by malloc:



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...