user3333976
user3333976

Reputation: 1

Issues with malloc in C

I seem to be having some issues with malloc in my code. Here's what's going on. I've got a struct created with a few values in it. From there, I'd like to make an array of structs. I think I've got the struct right, and some of the pointers, but I'm not sure.

Here's the struct:

typedef struct{
    char name[25];
    int courseID;
} course;

From there, I try to initiate the new struct and malloc it at the same time by this:

course *courses = malloc(25*sizeof(course));

From here, I'm getting the error:

Invalid conversion from 'void*' to 'course*' [-fpermissive] course *courses = malloc(25*sizeof(course));

I don't really know what this means... I know I may be completely off course with this whole idea, so any help y'all can give would be great!

Upvotes: 0

Views: 189

Answers (2)

Soumen
Soumen

Reputation: 1078

You are initializing memory with malloc, which returns a void pointer to the allocated memory. You are then assigning this pointer to a course pointer. So there is a pointer mismatch and hence the warning. To bypass it use

course *courses = (course *)malloc(25 * sizeof(course))

Upvotes: 0

Zan Lynx
Zan Lynx

Reputation: 54325

You must be using a C++ compiler. You want to compile with a C compiler.

Make sure your file name ends in .c not .cpp or .cc.

You also said you try to initialize (you said initiate but I am translating) the new struct. Malloc will not do that. Malloc allocated memory will contain random values left over from the last user of that memory. The calloc function might work better for what you want since it sets the memory to zero after allocating it.

Upvotes: 2

Related Questions