简体   繁体   中英

C: Warning when casting int to int* on Windows 64-bit machine when working on 32-bit program

I'm working on a legacy 32-bit program where there are a lot of casts like DWORD* a = (DWORD*)b , where b is a native int , and I get lots of these warnings:

Cast to 'DWORD *' (aka 'unsigned int*') from smaller integer type 'int' ['clang: -Wint-to-pointer-cast]

Since the sizes are equal during compilation it's fine, but I don't see how Clang would know that. What can I do to satisfy this warning other than disabling it entirely?

EDIT: The premise of the question is bad due to my misunderstanding of Clang, a compiler, and clangd, the language server which invokes Clang. The language server didn't know I was targeting x86.

So the problem is (DWORD*)b but b is of type int . This means the code needs to be redesigned, because somebody is stuffing pointers into int . Microsoft made a special type for a pointer-sized integer: DWORD_PTR . Yeah sure there's one in stdint.h and you can use that one if you want, but if you're already using DWORD you might as well use DWORD_PTR . The problem didn't happen on this line. The problem happened on the line where b was assigned the value from a pointer.

Change type of b to intptr_t , uintptr_t , or DWORD_PTR and back-propigate the change until the errors go away. If you come to a place where you can't, that part of the code needs to be redesigned.

Microsoft's own compiler now yields warnings for this stuff even in 32 bit compilation when the type isn't one of the pointer-in-integer types. Best to head the warnings.

Stuffing pointers in integers is not a recommended practice anymore, but the Win32 API does it all over the place, so when in Rome...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM