#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);
}
<小时/>
我编写了这段代码,但该变量正在打印如下值。 Int-4 的大小 短裤尺寸 - 2
当我执行 "int*iInt=&vShort ;"
时它也不起作用,它给出相同的输出。
输出:
空头值(value):3 iof 短值: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;
关于c - Short 到 Int 类型转换不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27358011/