I'm trying to use malloc() and sizeof() to create a struct on the heap. Here is my code:
#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;
}
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...
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));
Best practices for using malloc
:
struct Employee *p = malloc(sizeof *p);
You also need to fix your IDE/compiler to tell it you're writing C and not C++, since it's too broken to figure this out on its own...
Since some people seem unhappy with this answer (and with my disapproval of the other answers), I think I should explain why working around the problem is not good.
In C, casting the return value of malloc is harmful because it hides warnings if you forgot to include stdlib.h or otherwise prototype malloc. It also makes your code harder to maintain; all the answers with a cast require making 3 changes if the type of p needs to be changed, while my answer requires a change only in one place. Finally, new C programmers should not get in the bad habit of using casts whenever they see a compiler warning or error. This usually just buries bugs. Correct code almost never requires casts, and their use should be seen as a code smell
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With