I want to print addresses of member elements of a structure variable. When i try to compile this program it gives me error (error: cast from ‘uint8_t* {aka unsigned char*}’ to ‘unsigned int’ loses precision [-fpermissive]).I am using https://www.onlinegdb.com/online_c++_compiler. Note: i am using unsigned(ptr) otherwise it gives some ASCII characters.(If i defined pointer variable uint16_t ptr; ptr = (uint16_t)&data; Then it also works but not for 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++;
}
}
Using the online-compiler you provided and changing this line
cout<<hex<<unsigned(ptr)<<endl;
to
cout << hex << (uintptr_t) ptr << std::endl;
prints the addresses.
When checking the size of these datatypes using:
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;
the output is:
sizeof(uintptr_t) = 8
sizeof(uint8_t*) = 8
sizeof(unsigned int) = 4
The pointer-size is 8 byte while your unsigned int
type has only a size of 4 bytes. That's why this error appears. The upper 8 byte are cut off and the address wouldn't be correct.