0

I have a struct pointer that I want to dynamically allocate memory.

struct employeeStructure {
  char name[100];
  char address[255];
  int age;
  char ssnum[100];
};
typedef struct employeeStructure employee;
  /* and in my main function */
employee *employeeRecord;
employeeRecord = malloc(sizeof(employee));
->>>
->>> error: assigning to 'employee *' (aka 'employeeStructure *') from incompatible type 'void *'
->>>

And I got an error: assigning to 'employee *' (aka 'employeeStructure *') from incompatible type 'void *'.

1
  • 5
    You seem to be compiling C code as if it was C++. Compile it as C and the error will go away. Aug 9, 2014 at 8:22

3 Answers 3

8

C++ will give this error, so you're probably using a C++ compiler.

Change the settings to C, or add an explicit cast, as C++ requires (or switch to using new/delete).

In C, adding an explicit cast to the return value of malloc is considered bad form. This is the primary reason that almost all C code is incompatible with a C++ compiler. Best thing is to consider C and C++ different languages and learn them separately.

Edit: See here as to why it's considered bad form.

0
2

you should provide more information about how you are compiling it. @PerJohansson gave already useful hints for you. to sum up, these are possible fixes to your error:

  • change line employeeRecord = malloc(sizeof(employee)); to employeeRecord = (employee*)malloc(sizeof(employee));. C++ requires malloc casts. people deducted from error you're getting that you're using C++ compiler.
  • use C compiler.

In my opinion, it's good to consider C and C++ as a seperate languages. so, if your program is meant to be C++, try using new instead of malloc. And always remember to free (if using malloc) or delete (if using new) the variables that you've allocated (you didn't provide a full code, so i don't know whether you're doing it or not).

1

This is because malloc returns void *. You probably requires to cast it as per your requirements. There in no need generally to cast every malloc object. But it is recommended to cast it as per programmers need. This code can be helpful:

employeeRecord = ( employee * )malloc(sizeof(employee));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.