Is it possible to cast a char * to a struct?
Here is my issue, one of the rcvfrom() parameters is a char * and once I got the data from it I want to convert it to a struct. However, the cast is unsuccessful. What am I doing wrong?
Here is what I did:
struct {
int8_t seq;
int8_t ack;
bool flag;
char data[payload];
}r_pckt;
//...bunch of codes
char *buf = NULL;
buf = (char *)malloc (sizeof(char) * MTU);
memset(buf, 0, MTU);
//...
res = recvfrom(socket_fd, buf, MTU, 0,(struct sockaddr *) &cli_addr, (socklen_t *)&cli_len);
//..
r_pckt *tmp_pckt = (struct r_pckt *) &buf;
And it does not work. Any id开发者_如何学Goeas? Thanks.
typedef struct {
int8_t seq;
int8_t ack;
bool flag;
char data[payload];
} r_pckt;
The above makes r_pckt a type, not a variable. Then,
r_pckt *tmp_pckt = (struct r_pckt *) &buf;
should be
r_pckt *tmp_pckt = (r_pckt *) buf;
r_pckt is not a struct name, but variable name. Try
struct r_pckt {
int8_t seq;
int8_t ack;
bool flag;
char data[payload];
};
And yes, Mark is right, you need no & there.
P.S. Actually, when "it does not work", it also provides you with meaningful error messages that are worth reading.
You need to remove the & in the cast. And (as others already pointed out), you have an inconsistency in the structure definition and the variable declaration. I think most compilers would catch that, so I suspect a cut-n-paste error when posting the question.
struct r_pckt *tmp_pckt = (struct r_pckt *) buf;
r_pckt *tmp_pckt = (struct r_pckt *) &buf;
should be:
r_pckt *tmp_pckt = (struct r_pckt *) buf;
The buf variable is a pointer type and already points to the memory allocated via malloc. Taking the address of it gives you the address of the memory holding the address of your data.
edit: Also fix the structure declaration as per Michael's post and you'll be set.
精彩评论