Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

udp

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.

like image 727
fabricemarcelin Avatar asked Mar 30 '11 20:03

fabricemarcelin


1 Answers

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;
like image 176
Erik Avatar answered Oct 05 '22 23:10

Erik