Reputation: 31
#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:
65512
65514
65516
65518
65520
But when I change the printf
to"
printf("%u",&j[i]);
Output is:
65512
65516
65520
65524
65528
Why the address differ by 2 in first case and 4 in second casee?
What is wrong with just printing j
and printing &j[i]
?
Upvotes: 1
Views: 126
Reputation: 27268
First, just to make it clear, you are printing the pointer j
, and not the pointed value, *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)
. i
is incremented in each iteration, which contributes 2 to the pointer's value, and j
is incremented too, which contributes another 2.
Upvotes: 0
Reputation: 272687
You get jumps of 4 in the second example because you are incrementing j
and offsetting by i
! Both of these contribute a difference of 2.
Note also that printf
is not type-safe; it is up to you to ensure that the arguments match the format-specifiers. You have specified %u
, but you've given it an int *
, you should use %p
for pointers.
Upvotes: 3