error: cast from ‘uint8_t* {aka unsigned char*}’ to ‘unsigned int’ loses precision [-fpermissive]

error: cast from ‘uint8_t* {aka unsigned char*}’ to ‘unsigned int’ loses precision [-fpermissive]

我想打印结构变量的成员元素的地址。当我尝试编译这个程序时它给我错误(错误:从'uint8_t* {aka unsigned char*}'转换为'unsigned int'失去精度[-fpermissive])。我正在使用https://www.onlinegdb.com/online_c++_compiler.注意:我正在使用 unsigned(ptr) 否则它会给出一些 ASCII 字符。(如果我定义了指针变量 uint16_t ptr; ptr = (uint16_t)&data;然后它也适用但不适用于 uint8_t.)

#include <iostream>
using namespace std;

struct DataSet
{
    char  data1;
    int   data2;
    char  data3;
    short data4;
};

int main(void)
{
    struct DataSet data;

    data.data1  = 0x11;
    data.data2  = 0XFFFFEEEE;
    data.data3  = 0x22;
    data.data4  = 0xABCD;

    uint8_t *ptr;
    ptr = (uint8_t*)&data;

    uint32_t totalSize = sizeof(struct DataSet);
    
    for(uint32_t i = 0 ; i < totalSize ; i++)
    {
        cout<<hex<<unsigned(ptr)<<endl;  // Here i get error.So how can i print these addresses using uint8_t.
        ptr++;
    }
}

使用您提供的 online-compiler 并更改此行

cout<<hex<<unsigned(ptr)<<endl;

cout << hex << (uintptr_t) ptr << std::endl;

打印地址。

当使用以下方法检查这些数据类型的大小时:

std::cout << "sizeof(uintptr_t) = " << sizeof(uintptr_t) << std::endl;
std::cout << "sizeof(unsigned int) = " << sizeof(uint8_t*) << std::endl;
std::cout << "sizeof(unsigned int) = " << sizeof(unsigned int) << std::endl;

输出是:

sizeof(uintptr_t) = 8
sizeof(uint8_t*) = 8                                                                                                                                                                                                                                                                                                                     
sizeof(unsigned int) = 4   

pointer-size 是 8 个字节,而您的 unsigned int 类型只有 4 个字节。这就是出现此错误的原因。高 8 字节被截断,地址不正确。