是否可以将 char * 转换为结构?转换为、结构、char

2023-09-07 13:17:14 作者:啃猪蹄的小仙女

这是我的问题,rcvfrom() 参数之一是 char *,一旦我从中获取数据,我想将其转换为结构.然而,演员阵容并不成功.我做错了什么?

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?

这是我所做的:

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.

推荐答案

typedef struct {
   int8_t seq;
   int8_t ack;
   bool flag;
   char data[payload];
} r_pckt;

以上内容使 r_pckt 成为类型,而不是变量.那么,

The above makes r_pckt a type, not a variable. Then,

r_pckt *tmp_pckt = (struct r_pckt *) &buf;

应该是

r_pckt *tmp_pckt = (r_pckt *) buf;