Int类型转换不适用为什么?

-3 c int casting short

#include <stdio.h>

main()
{
short vShort=3;
int *iInt=(int *)&vShort ;
printf("Value of short: %d\n",vShort);
printf("Value iof short: %d\n",*iInt);
}
Run Code Online (Sandbox Code Playgroud)

我写了这段代码,但是这个变量是打印valus,如下所示.Int-4尺寸的短尺寸 - 2

当我这样做时它也没有工作"int*iInt=&vShort ;"给出相同的输出.

输出:

短期价值:3价值短期:196608

rub*_*nvb 6

这里,

 int *iInt=(int)&vShort
Run Code Online (Sandbox Code Playgroud)

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

如果你想以"铸造"一shortint,就为它分配,整数推广会照顾一切:

short s = 3; // note that this line already technically casts the integer literal 3 to type short
int i = s;
Run Code Online (Sandbox Code Playgroud)

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

short s = 3;
int i; // if you add "= s" here you can drop the last line
int* iptr = &i;
*iptr = s;
Run Code Online (Sandbox Code Playgroud)