C - Pointer + 1 Value

Basically, these codes print the address of each element in int and char arrays, which i and ch pointers point to.

#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 the bulk size of its data type. My problem is that I am confused by this operation:

 i+1 

If i is 00511068, then i+1 00511069 in contrast to the result. What does i+1 mean? How do you read it? I think I do not quite understand the pointer. Please help me figure this out. Thanks.

+4
source share
3 answers

Oh yes, this old chestnut. There's a bit of magic going on when you add N to the pointer; the compiler determines that you want the address of the Nth element, and multiplies the offset by the size of the data type.

+8
source

This is because int is 4 bytes in this system. So +1 on the pointer will increment it by 4 instead of 1.

When you increase the pointer, you increase it by the actual size, not by the value of the pointer.

+10
source

pointer + j matches &(pointer[j]) , so its address is j: th of the element in the array pointed to by pointer . Obviously, a pointer to a large data type will increase more than a pointer to a small data type.

+4
source

All Articles