问题说明:
用socket实现结构体变量的传输,
struct student
{
    int id;  //4字节
    char name[20];  //20字节
    float goal;     //8字节
}
传输部分,可以这样实现
student stu;
//socket sock;
mencpy(buff,student,sizeof(student));
send(sock,buff,sizeof(student),0);    //暂且这么实现接受端:
定义buff[32];
recv( sock, buff, 32,0);
那怎么把buff中的内容,还原成struct中的成员变量呢?  

解决方案 »

  1.   

    student* stu = (student*)buff;
    这样不行吗?
      

  2.   

    student* stu
    stu = (student*)buff;
    int recv_id=stu->id;
    ....
    试试 看行不行!
      

  3.   

    这个是什么想法,直接把接受来的buff强制转换为student型的指针吗?
      

  4.   


    这么想哪里错了?把buff的首地址强制转换为student类型的指针好像么错啊,结构体在内存中存储的内容是连续的,bufff也是连续的,可以直接转换
      

  5.   

    是这样的,在发送之前调用了memcpy(buff,student,sizeof(student));将存储student类型的内存拷贝到了Buff中,并发送,接收的Buff此时也存储的是student类型的内存,所以通过将buff强制转换为student型的指针,可以正确的解析发送时候的数据
      

  6.   

    如果在不通的操作系统传输,特别注意,是不可靠的。
    因为不同的系统对sizeof的理解不一样,int arm中可能是6byte 也可能是4byte.
    不要用结构传输!!!!