c语言 - 短路到int类型转换不起作用,为什么?


#include <stdio.h>
main()
{
short vShort=3;
int *iInt=(int *)&vShort ;
printf("Value of short: %dn",vShort);
printf("Value iof short: %dn",*iInt);
}

我写了这段代码,但这个变量正在打印价值,如下所示。国际-4的尺寸短码 - 2

当我这样做时它也无法正常工作"int*iInt=&vShort ;"它提供了相同的输出。

输出:

短值:3值 iof short: 196608

在这里,

 int *iInt=(int)&vShort

您正在将变量的地址强制转换为int(这是未定义的行为,或者至少是定义的实现,因为整数可能不足以容纳指针的值,只有uintptr_t)。

如果你想将一个short"投射"到一个int,只需分配它,整数提升将处理一切:

short s = 3; // note that this line already technically casts the integer literal 3 to type short
int i = s;

如果你想要一个指向int值的指针,你需要创建一个局部变量并获取它的地址,或者使用malloc为其分配内存:

short s = 3;
int i; // if you add "= s" here you can drop the last line
int* iptr = &i;
*iptr = s;
实际上,

这种类型的代码已经存在于我们的系统中,可以删除警告开发人员键入的短到int。 这就是为什么我发布了这个问题,这段代码有什么问题。

相关内容

最新更新