[英]Why this c program output like this?
#include<stdio.h>
main
{
int x[]={1,2,3,4,5};
int i,*j;
j=x;
for(i=0;i<=4;i++)
{
printf("%u",j);
j++;
}
}
output: output:
65512
65514
65516
65518
65520
But when I change the printf
to"但是当我将
printf
更改为“
printf("%u",&j[i]);
Output is: Output 是:
65512
65516
65520
65524
65528
Why the address differ by 2 in first case and 4 in second casee?为什么地址在第一种情况下相差 2,在第二种情况下相差 4?
What is wrong with just printing j
and printing &j[i]
?只打印
j
和打印&j[i]
有什么问题?
You get jumps of 4 in the second example because you are incrementing j
and offsetting by i
.在第二个例子中你得到了 4 的跳跃,因为你增加了
j
并偏移了i
。 Both of these contribute a difference of 2.这两者都贡献了 2 的差异。
Note also that printf
is not type-safe;还要注意
printf
不是类型安全的; it is up to you to ensure that the arguments match the format-specifiers.您可以确保 arguments 与格式说明符匹配。 You have specified
%u
, but you've given it an int *
, you should use %p
for pointers.你已经指定了
%u
,但是你给了它一个int *
,你应该使用%p
作为指针。
First, just to make it clear, you are printing the pointer j
, and not the pointed value, *j
首先,为了清楚起见,您正在打印指针
j
,而不是指向的值*j
Now, regarding the printed address.现在,关于打印的地址。 In your second example:
在您的第二个示例中:
for(i=0;i<=4;i++)
{
printf("%u",&j[i]);
j++;
&j[i]
equals to (j+i)
. &j[i]
等于(j+i)
。 i
is incremented in each iteration, which contributes 2 to the pointer's value, and j
is incremented too, which contributes another 2. i
在每次迭代中递增,这为指针的值贡献了 2, j
也递增,这又贡献了 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.