c - Short 到 Int 类型转换不起作用,为什么?

标签 c casting int 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);
}
<小时/>

我编写了这段代码,但该变量正在打印如下值。 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/

相关文章:

c# - Int to Decimal Conversion - 在指定位置插入小数点

c++ - 无符号与有符号整数的性能

c - 我收到运行时错误 : Segmentation Fault (SIGSEGV),,为什么?

ios - 将 NSData 转换为! swift 2.0 中的 CFDataRef

java - 在 mvel 中将字符串转换为整数

java - java中的类转换

c - C 中的数字螺旋,代码不起作用

c++ - 为什么事件轮询循环中的函数触发频率低于其外部的函数

c - 创建用户登录后如何编程创建新的显示菜单选择?

c# - int.TryParse 之前的空检查