是否可以将 char * 转换为结构? [英] Is it possible to cast a char * to a struct?
本文介绍了是否可以将 char * 转换为结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的问题,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;
这篇关于是否可以将 char * 转换为结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文