是否有可能投一个char *一个struct? [英] Is it possible to cast a char * to a struct?
本文介绍了是否有可能投一个char *一个struct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的问题,rcvfrom()的一个参数是char *,一旦我得到了从它的数据我想将它转化成一个结构。不过,中投不成功。我在做什么错了?
下面是我做过什么:
结构{
以次中int8_t;
ACK中int8_t;
布尔标志;
CHAR数据[负载]
} r_pckt;
的codeS //...bunch字符* BUF = NULL;
BUF =(字符*)malloc的(的sizeof(char)的* MTU);
memset的(BUF,0,MTU);
// ...RES = recvfrom的(socket_fd,BUF,MTU,0,(结构sockaddr *)及cli_addr,(socklen_t的*)及cli_len);
// ..
r_pckt * tmp_pckt =(结构r_pckt *)及BUF;
和它不工作。有任何想法吗?
谢谢你。
解决方案
typedef结构{
以次中int8_t;
ACK中int8_t;
布尔标志;
CHAR数据[负载]
} r_pckt;
上面使得r_pckt一个类型,而不是一个变量。然后,
r_pckt * tmp_pckt =(结构r_pckt *)及BUF;
应
r_pckt * tmp_pckt =(r_pckt *)BUF;
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.
解决方案
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;
这篇关于是否有可能投一个char *一个struct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文