Is it possible to cast a char * to a struct?

2019-04-12 13:16发布

问题:

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 ideas? Thanks.

回答1:

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;


回答2:

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.



回答3:

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;


回答4:

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.



标签: c udp