我试图理解指针,它们的值和类型
假设我有一个整数x:
int x = 0;
int* ip = &x;
我知道这里的值是x的地址,假设它是123。
*ip += 1
现在的值是124吗? (地址+ 1)。我试图了解该值会发生什么,然后在此处键入:
float *fp = (float*)ip;
*fp = 1.0;
int y = *ip;
答案 0 :(得分:4)
如果将指针设置为变量的地址,然后进行取消引用分配,则将更改指针处的值,而不是地址本身。因此,如果您写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
答案 1 :(得分:0)
int x = 0;
int* ip = &x; /*I know the value here is the address of x, let's say it is 123*/
printf("\n%u",ip); //value is 123
printf("\n%u",*ip);// value is 0
*ip += 1; //*ip points to the value of the stored address i.e. x and increase it by 1
printf("\n%u",ip); //value is 123
printf("\n%u",*ip); //value is 1
float *fp = (float*) ip; converting address inside ip i.e. 123 into float type and store in fp
printf("\n%u",fp); //value is 123
printf("\n%f",*fp);//points to the value of stored address i.e. value at 123. 0.000000 is the value as we have converted it to float from int it got initialized to 0
*fp = 1.0; //storing the value to address 123
printf("\n%f",*fp);//value is 1.000000
int y = *ip;//storing the value
printf("\n%f",y);//it will also gives 1.000000
这里我不解释float和int之间的内部转换。只是解释指针的工作原理