1
votes

I'm really raw with C, and am having trouble with a cast. Here are the lines of my code that I think are relevant:

#define BUF 1025
char hostname[BUF];

hostname = *(char *) qpop(&queue);

And this is the error that I am getting from the compiler:

error: incompatible types when assigning to type 'char[1025]' from type char

Note that the function qpop returns a void*. I think that my issue is how to cast from a void* into char[1025]. From the error message, I seem to be casting to type char, but not to type char[1025]. I tried this:

hostname = *(char[1025] *) qpop(&queue)

but that didn't work either.

Can somebody help me understand how to do this? Thank you!

2
the proper way to cast is without the first asterisk: char_ptr=(char*)void_ptr; - Leo supports Monica Cellio
@NannuoLei: Actually, the proper way is to not cast at all. void* needs no casting to assign it to another pointer type. Additionally, the extra * isn't doing any casting at all, it's doing a dereference. - Cornstalks
@Cornstalks thanks for the enlightenment. I know you're right about void, I just forgot about that and stepped directly into explaining how to cast anything (other than void*). And yes, the first * is for dereference. - Leo supports Monica Cellio

2 Answers

6
votes

Arrays are not first-class types. You cannot assign to an array. You have to copy the memory/elements into the array:

memcpy(hostname, qpop(&queue), BUF)
1
votes

Casting does not make sense. because you can't assign a pointer to array directly. FYI the syntax is :hostname = (char(*)[1025]) qpop(&queue) . you can read this as "pointer to array of 1025 chars"

The best Solution is give by @Cornstalks