Tuesday 22 October 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...