以下代码中ii =(char *)& i和a =(char *)& a的含义是什么

时间:2015-06-30 12:51:31

标签: c

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
animation.duration = 1.0;
animation.path = path.CGPath;
[view.layer addAnimation:animation forKey:@"myPathAnimation"];

#include<stdio.h> int main() { int i = 5; float a = 3.14; char*ii,*aa; ii = (char*)&i; aa = (char*)&a; printf("address contained in ii=%u\n",ii); printf("address contained in aa=%u\n",aa); printf("value at address contained in ii=%d\n",*ii); printf("value at address contained in aa= %d\n",*aa); return(0); } /*the output for the following program was address contained in ii=65524 address contained in aa=65520 value at address contained in ii=5 value at address contained in aa=-61*/ ii = (char*) &i的含义是什么?为什么编译器在aa = (char*) &a的地址打印值是正确的,而ii中的值是错误的?如果您使用aa的任何其他值,例如327,则i中包含的地址值将变为其他值。有人可以向我解释一下吗?我无法从编写代码的书中得到适当的解释。

程序源:了解c中的指针。作者:yashvant kanetkar,第4版。

1 个答案:

答案 0 :(得分:1)

The program as given in the book is an example of what not to do:

Don't try to access a value through a pointer when the pointer is not a pointer to the same type as the original value.

In the book, i is an int, but the code deliberately makes a char* point to the integer. So, when ii is dereferenced you just get a value that seems to be a char.

edit: So, the expression (char*)&i; first takes the address of i, which the compiler thinks of as type int* and then converts the type to char* without changing the value of the pointer.

The important thing to note about the different types of pointers is that they often imply a different size of object pointed to.

Also note that the output of all the whole program will depend on the platform you are using.