Reputation: 30093
What the codes basically do is to print the address of each element in the int and char arrays pointed to by pointers i and ch.
#include<stdio.h>
int main()
{
char *ch;
int *i;
int ctr;
ch = malloc(sizeof(char)*10);
i = malloc(sizeof(int)*10);
printf("Index\ti Address\tch Address\n\n");
for(ctr=0; ctr<10; ctr++)
{
printf("%d\t%p\t%p\n",ctr,i+ctr,ch+ctr);
}
getch();
return 0;
}
Result:
Index i Address ch Address
0 00511068 00511050
1 0051106C 00511051
2 00511070 00511052
3 00511074 00511053
4 00511078 00511054
5 0051107C 00511055
6 00511080 00511056
7 00511084 00511057
8 00511088 00511058
9 0051108C 00511059
I understand that each element in two arrays occupies space size of their data type. My problem is, I'm confused to this operation:
i+1
If i
is 00511068 , then i+1
is 00511069
as opposed to the result. What does i+1
means? How do you read it? I think I don't fully understand pointer. Please help me understand it. Thank you.
Upvotes: 5
Views: 25024
Reputation: 33273
pointer + j
is the same as &(pointer[j])
, so its the adress of the j:th element in the array pointed to by pointer
.
Obviously, a pointer to a large data type will be incremented more than a pointer to a small data type.
Upvotes: 5
Reputation: 8639
Ah, yes, that old chestnut. There's a bit of magic going on when you add N to a pointer; the compiler intuits that you want the address of the Nth item, and multiplies the offset by the size of the datatype.
Upvotes: 16
Reputation: 471199
This is because int
is 4 bytes on this system. So +1
on a pointer will increment it by 4 instead of just 1.
When you increment a pointer, you increment it by it's actual size and not the pointer value itself.
Upvotes: 12