C/C++结构体指针强转为整型/长整型

发布时间 2023-12-13 15:12:12作者: Labant

一、关键词

结构体指针强转为整型类,使用时在把整型强转为结构体指针

 

二、知识点

注意:1、这种的转化并不是用指针指向指针,而是目标指针的地址被作为一个值被保存在整型中,而整型中的值就是目标指针的地址。

   2、需要实在64位机器还是32为机器,在32位用int就可以,而64位需要long进行转化以及存储才会有效。

三、实际运用

struct my_struce {
    char chars;
    int ints;
    my_struce* my_struce_;
};
int main(argc i,argv c[])
{
    my_struce*  temp2;
    temp2 = (my_struce*)malloc(sizeof(my_struce));

    temp2->my_struce_ = (my_struce*)malloc(sizeof(my_struce));
    temp2->chars = QString("8.125f").data()->toLatin1();
    temp2->ints = 5120;
    memcpy((void*)temp2->my_struce_,(void*)temp2,sizeof(my_struce));

    long ttt = (long)temp2;  //!把指针转为数,把这个数存储到长整形当中,用时把这个数转为结构体指针(注意不是长整型地址,而是长整型本身)

    my_struce* temp_ptr_2 = (my_struce*)ttt;
    cou<<temp_ptr_2->my_struce_->ints;   
}