Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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...

like image 267
Ordo Avatar asked Dec 23 '10 14:12

Ordo


2 Answers

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));
like image 62
user470379 Avatar answered Oct 04 '22 03:10

user470379


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

like image 27
R.. GitHub STOP HELPING ICE Avatar answered Oct 04 '22 03:10

R.. GitHub STOP HELPING ICE