C++ 从较大的数据类型(struct)转换为较小的数据类型

C++ 从较大的数据类型(struct)转换为较小的数据类型,c++,memory,casting,C++,Memory,Casting,我已经知道一个结构的指针可以转换为另一个具有等效内存布局的结构指针 但是,在以下代码中: #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define MYPORT "3490" // the port users will be connecting to #define BACKLOG 10 //

我已经知道一个结构的指针可以转换为另一个具有等效内存布局的结构指针

但是,在以下代码中:

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MYPORT "3490"  // the port users will be connecting to
#define BACKLOG 10     // how many pending connections queue will hold

int main(void)
{
    struct sockaddr_storage their_addr;
    socklen_t addr_size;
    struct addrinfo hints, *res;
    int sockfd, new_fd;

    // !! don't forget your error checking for these calls !!

    // first, load up address structs with getaddrinfo():

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

    getaddrinfo(NULL, MYPORT, &hints, &res);

    // make a socket, bind it, and listen on it:

    sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    bind(sockfd, res->ai_addr, res->ai_addrlen);
    listen(sockfd, BACKLOG);

    // now accept an incoming connection:

    addr_size = sizeof their_addr;
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);

    // ready to communicate on socket descriptor new_fd!
    .
    .
    .
以及:


socktaddr_存储肯定是一个更大的信息存储,因此它可以转换为任何比它小的存储,以适合函数声明。在函数内部,结构的类型无关紧要,只要传递到函数中的结构有足够的内存块使函数能够作为所需的结构运行。这是正确的吗?

是的,它是正确的。基本上,它类似于将派生类指针转换为基类指针(事实上,这就是它在C中的实现方式)


14字节的内容将根据<代码> SSHORACHOR> <代码>的值设置,然后你可以将它转换为.< /P>这是适用于C++中的,因为C++已经有4种类型的铸造(我猜这只是C铸造的包装)?另外,你在Beej指南上给了我一个正确的答案:)这是一个普通的旧C转换,因为你用C数据调用C函数,这很好。将其与对象指针一起使用会很危险。你可以,如果你想,使用C++的Cub运算符代替C,但是我不会。<代码> SAODATA(14)< /C>应该是代码> SAODATA(46)< /C> >以防万一<代码> SAWORACHON/CODE >原来是<代码> AFJ-ITE6。如果缓冲区太小,它将失败。

addr\u size=sizeof the_addr将给您4,因为它是一个ptr<代码>*他们的地址需要延迟才能获得正确的长度。
struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
}; 
struct sockaddr_storage {
    sa_family_t  ss_family;     // address family

    // all this is padding, implementation specific, ignore it:
    char      __ss_pad1[_SS_PAD1SIZE];
    int64_t   __ss_align;
    char      __ss_pad2[_SS_PAD2SIZE];
};