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

2019-04-12 13:24发布

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.

标签: c udp
4条回答
放我归山
2楼-- · 2019-04-12 13:32

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楼-- · 2019-04-12 13:37

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;
查看更多
可以哭但决不认输i
4楼-- · 2019-04-12 13:50
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;
查看更多
放荡不羁爱自由
5楼-- · 2019-04-12 13:56
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.

查看更多
登录 后发表回答