使用指针Ç问题 [英] C question with pointers
问题描述
我有一个程序问题,这里是code。
I have a program question, here is the code.
int main()
{
int *p,*q;
p=(int*)1000;
printf("%d ",p);
q=(int*)2000;
printf("%d",q);
printf("%d",(p-q));
return 0;
}
但答案即将为
1000
2000
-250
我无法理解有什么发生 P-Q
为什么答案之际, -250
?
推荐答案
正确的,但可能是没用的回答:对 - q
等于(1000 - 2000)/(sizeof的INT)
。对于大多数C编译,的sizeof INT
4。
Correct but probably useless answer: p - q
is equal to (1000 - 2000) / (sizeof int)
. For most C compiles, sizeof int
is 4.
更多潜在有用的答案:类型转换的像的效果(INT *)1000
是不确定的。这code创建一个指向int的地址1000 的。这个地址很可能是无效的。要创建一个指向与价值1000一个int,这样写:
Potentially more useful answer: the effect of typecasts like (int*) 1000
is undefined. That code creates a pointer to an int at address 1000. That address is probably invalid. To create a pointer to an int with value 1000, write this:
int i = 1000;
int *p = &i;
现在 P
点 I
和 * P
,该值指向 p
1000
Now p
points to i
, and *p
, the value pointed to by p
, is 1000.
下面是一些正确的code,可能会说你的意思:
Here is some correct code that may say what you meant:
int main() {
int i = 1000;
int j = 2000;
int *p = &i;
int *q = &j;
printf("i = %d *p = %d\n", i, *p);
printf("j = %d *q = %d\n", j, *q);
printf("*p - *q = %d\n", *p - *q);
}
这篇关于使用指针Ç问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!