Printing the structure object address

I have a struct like this

 typedef struct _somestruct { int a; int b; }SOMESTRUCT,*LPSOMESTRUCT; 

I create an object for struct and try to print its address as follows

 int main() { LPSOMESTRUCT val = (LPSOMESTRUCT)malloc(sizeof(SOMESTRUCT)); printf("0%x\n", val); return 0; } 

.. and I get this warning

warning C4313: 'printf': '% x' in formatting conflicts with argument 1 of type 'LPSOMESTRUCT'

So, I tried to specify the int address as follows

 printf("0%x\n", static_cast<int>(val)); 

But I get this error:

error C2440: 'static_cast': cannot convert from 'LPSOMESTRUCT' to 'int'

What am I missing here? How to avoid this warning?

Thanks.

+4
source share
4 answers

%x expects unsigned. What you type is a pointer. To do this correctly, you usually want to use %p . To be pedantically correct, which expects the pointer to be invalid, you will need to drop it:

 printf("%p\n", (void *)val); 

In fact, most modern implementations use the same format for all pointers, in which case casting will be empty. Of course, given the C ++ tag, most of the code that you included becomes dubious at best (with the exception of parts like LPSOMESTRUCT, which are dubious independently). In C ++, you usually want something more:

 struct somestruct { int a; int b; }; somestruct *val = new somestruct; // even this is questionable. std::cout << val; 
+11
source

Use the% p format specifier to print the pointer.

 printf("%p\n", val); 
+2
source

If you want to use, then using reinterpret_cast instead of static_cast can do the trick here.

With printf, try using% zu instead of% x to print the pointer, because the pointer is an unsigned integer type (i.e.% zu).

 printf("%zu \n", val); 

Just one more thing, being a C ++ program, is there a reason why you are using malloc instead of the new one?

+1
source

Since this is labeled C ++, can I just point out that you don't need typedefs when creating structures in this language:

 typedef struct _somestruct { int a; int b; }SOMESTRUCT,*LPSOMESTRUCT; 

it should be:

 struct SOMESTRUCT { int a; int b; }; 

In addition, many consider it a bad practice to create typedefs, such as LPSOMESTRUCT, that hide the fact that the type is a pointer.

+1
source

Source: https://habr.com/ru/post/1312731/


All Articles