简体   繁体   English

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

[英]Is it possible to cast a char * to a struct?

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. 这是我的问题,其中一个rcvfrom()参数是一个char *,一旦我从中获取数据,我想将其转换为结构。 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. 上面使r_pckt成为一个类型,而不是一个变量。 Then, 然后,

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

should be 应该

r_pckt *tmp_pckt = (r_pckt *) buf;

r_pckt is not a struct name, but variable name. r_pckt不是结构名称,而是变量名称。 Try 尝试

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

And yes, Mark is right, you need no & there. 是的,马克是对的,你不需要那里。

PS Actually, when "it does not work", it also provides you with meaningful error messages that are worth reading. PS实际上,当“它不起作用”时,它还会为您提供值得阅读的有意义的错误消息。

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;
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. buf变量是指针类型,并且已经指向通过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. 编辑:根据迈克尔的帖子修复结构声明,你将被设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM