C语言 从以下代码中获取警告“从不同大小的整数转换为指针”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5701450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:26:12  来源:igfitidea点击:

Getting the warning "cast to pointer from integer of different size" from the following code

cgccgcc-warning

提问by thetna

The code is:

代码是:

           Push(size, (POINTER)(GetCar(i) == term_Null()? 0 : 1));

Here is the C code pushreturns ABCwhich is

这里是 C code push回报 ABC这是

 typedef POINTER  *ABC
 typedef void * POINTER
 ABC size;
 Push(ABC,POINTER);
 XYZ GetCar(int);
 typedef struct xyz *XYZ;
 XYZ term_Null(); 
 long int i;

What is the reason for the particular warning?

特别警告的原因是什么?

回答by anatolyg

You can use intptr_tto ensure the integer has the same width as pointer. This way, you don't need to discover stuff about your specific platform, and it will work on another platform too (unlike the unsigned longsolution).

您可以使用intptr_t来确保整数与指针具有相同的宽度。这样,您不需要发现有关您的特定平台的内容,并且它也可以在另一个平台上运行(与unsigned long解决方案不同)。

#include <stdint.h>

Push(size, (POINTER)(intptr_t)(GetCar(i) == term_Null()? 0 : 1));

Taken from the C99 Standard:

取自 C99 标准:

7.18.1.4 Integer types capable of holding object pointers

1 The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

intptr_t

7.18.1.4 能够保存对象指针的整数类型

1 下面的类型指定了一个有符号整数类型,它的属性是任何有效的指向 void 的指针都可以转换为这种类型,然后转换回指向 void 的指针,结果将与原始指针相等:

intptr_t

回答by orlp

What are you trying to do? Pointers are not integers, and you are trying to make a pointer out of 0or 1, depending on the situation. That is illegal.

你想做什么?指针不是整数,您正试图根据情况从0或 中创建一个指针1。那是非法的。



If you were trying to pass a pointer to a ABCcontaining 0or 1, use this:

如果您试图将指针传递给ABC包含的0or 1,请使用以下命令:

ABC tmp = GetCar(i) == term_Null()? 0 : 1;
Push(size, &tmp);

回答by MByD

You are trying to cast an integer value (0 or 1) to a void pointer.

您正在尝试将整数值(0 或 1)转换为空指针。

This expression is alwaysan int with value 0 or 1: (GetCar(i) == term_Null()? 0 : 1)

此表达式始终是值为 0 或 1 的 int:(GetCar(i) == term_Null()? 0 : 1)

And you try casting it to void pointer (POINTER)(typedef void * POINTER).

您尝试将其强制转换为 void 指针(POINTER)( typedef void * POINTER)。

Which is illegal.

这是非法的。

回答by Bob Prystanek

Since this question uses the same typedefs as your 32bit to 64bit porting question I assume that you're using 64 bit pointers. As MByd wrote you're casting an int to a pointer and since int isn't 64 bit you get that particular warning.

由于这个问题使用与您的 32 位到 64 位移植问题相同的 typedef,我假设您使用的是 64 位指针。正如 MByd 所写,您将 int 转换为指针,并且由于 int 不是 64 位,因此您会收到该特定警告。