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

I am trying to use malloc () and sizeof () to create a structure on a 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 string struct Employee* p = malloc(sizeof(struct Employee));that the type "void *" cannot be converted to the type "Employee *". I do not know what is wrong here. The struct Employee seems to be invalid, but I don't understand why ...

+3
source share
5 answers

In C ++ (since you use Visual C ++ to compile), you must explicitly specify the pointer returned malloc:

struct Employee* p = (struct Employee*) malloc(sizeof(struct Employee));
+11
source

Recommendations for use malloc:

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

IDE/, , C, ++, , ...

( ), , , .

C malloc , , stdlib.h malloc. ; 3 , p, . , C , . . ,

+11

malloc .

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

malloc chunck (void *). , , chunck .

+1

C, .

++ void* Employee* .

something.c? , ?

++, , :

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

, malloc, void*. , p, Employee*. ++ ( C) void* . :

struct Employee* p = reinterpret_cast<Employee*>(malloc(sizeof(struct Employee))); 
0

Source: https://habr.com/ru/post/1781850/


All Articles