简体   繁体   English

从不同大小的整数转换为指针(将int作为const void *参数传递)

[英]Cast to pointer from integer of different size (passing int as a const void * parameter)

I have to maintain a chunk of source code on Linux with gcc which has the following function prototype: 我必须使用gcc维护Linux上的大量源代码,该代码具有以下功能原型:

int foo(const void*, ...)

I have to pass an integer into this function. 我必须将一个整数传递给此函数。 I know that this is a bad idea but at this stage, I'm not allowed to modify the source code. 我知道这是个坏主意,但是在现阶段,我不允许修改源代码。

ie I have to call foo(n) ( n is defined as int n ) 即我必须调用foo(n)n定义为int n

On a 64-bit machine, I get an error: 在64位计算机上,出现错误:

cast to pointer from integer of different size

As I understand, this is because the size of an integer on a 32-bit machine is four bytes while the size of a pointer to a void is eight bytes. 据我了解,这是因为32位计算机上整数的大小为4个字节,而指向void的指针的大小为8个字节。

I resolve the compilation error by first casting the integer with size 4 bytes to a long with size 8 bytes. 我通过首先将大小为4个字节的整数转换为大小为8个字节的long来解决编译错误。 So I did foo((long)n) 所以我做了foo((long)n)

I wonder if this is an acceptable way to deal with this issue or are there other suggestions? 我想知道这是否是解决此问题的可接受方法,或者还有其他建议吗?

You could use intptr_t , but it is optional and may not be available in stdint.h : 您可以使用intptr_t ,但是它是可选的,可能在stdint.h不可用:

intptr_t n = 1;
foo((void*)n);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从指针转换为不同大小的 integer [-Wpointer-to-int-cast] - cast from pointer to integer of different size [-Wpointer-to-int-cast] 从指针强制转换为不同大小的整数[-Wpointer-to-int-cast] - cast from pointer to integer of different size [-Wpointer-to-int-cast] 将参数作为int传递给线程-警告:从不同大小的整数强制转换为指针 - Passing argument as int to thread - Warning: cast to pointer from integer different size 指针转换不兼容的整数,将“ int”传递给类型为“ const char *”的参数 - Incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' 从'void *'赋值给'int'使得integer从指针没有强制转换 - assignment to 'int' from 'void *' makes integer from pointer without a cast 警告:从指针转换为不同大小的整数[-Wpointer-to-int-cast] - warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] 警告:从指针转换为不同大小的整数 [-Wxpointer-to-int-cast] - warning: cast from pointer to integer of different size [-Wxpointer-to-int-cast] gcc.exe 警告从指针转换为不同大小的整数 [-Wpointer-to-int-cast] - gcc.exe warning cast from pointer to integer of different size [-Wpointer-to-int-cast] 从不同大小的整数转换为指针 - Cast to pointer from integer of different size memcpy-从不同大小的整数转换为指针 - memcpy - cast to pointer from integer of different size
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM