我试图理解指针,它们的值和类型
假设我有一个int x:
int x = 0;
int* ip = &x;
我知道这里的值是x的地址,假设它是123。
*ip += 1
现在的值是124吗? (地址+ 1)。我试图了解该值发生了什么,然后在此处键入:
float *fp = (float*)ip;
*fp = 1.0;
int y = *ip;
最佳答案
如果将指针设置为变量的地址,然后进行取消引用分配,则将更改指针处的值,而不是地址本身。因此,如果您编写更改地址的ip += 1
,而*ip +=1
更改了地址处的值。
这是一堆示例,这些示例应该有助于弄清指针的工作方式,包括浮点值。您应该阅读有关32位浮点数的IEEE754表示法,以更好地理解1.0
为什么表示为0x3f800000
。
请注意,此代码对类型的大小(由实现定义!)进行了很多假设,并且忽略了别名规则(不允许指向内存中对象的指针类型与声明的类型不匹配的对象)。对象,然后取消引用该指针)。也就是说,实际上,您始终可以将任何内存解释为位,即使它是“不安全的”或“非法的”。
int x = 0;
int* ip = &x;
*ip += 1; // x = 1
ip += 1; // ip is now increased by sizeof(int) and probably points to
// the gap in the stack between x and ip, since sizeof(x) is probably 4
// and ip is probably 8 byte aligned
ip += 1; // now ip probably points to itself! (the address points to its own address value)
ip -= 2; // now ip points to x again
*ip += 2; // now x = 3
float *fp = (float*)ip; // the value *fp is the same in binary, 0b11
int z = *(int *)fp; // z is 3, because we're preventing the conversion
*fp = 1.0; // in hex, *fp is 0x3f800000
int y = *fp; // 1.0 is converted to int and stored in y as 1
int a = *(int *)fp; // a is 0x3f800000