Addition and Subtraction of C Pointers

When we add an integer value to a pointer, the amount added is actually the number multiplied by the number of bytes in the underlying data type. As the compiler is aware of the data type size, pointer values can be automatically adjusted in a portable fashion.

#include <stdio.h>

int main(void){
    int nums[] = {16, 42, 69, 97, 126};
    int *ptr = nums;
    printf("nums[0] %p\t%d\n", ptr, *ptr);
    printf("nums[1] %p\t%d\n", ptr + 1, *(ptr + 1));
    printf("nums[2] %p\t%d\n", ++ptr + 1, *(ptr + 1));
    printf("nums[3] %p\t%d\n", ptr + 2, *(ptr + 2));
    printf("nums[4] %p\t%d\n", ++ptr + 2, *(ptr + 2));
    return 0;

When an array name is used without an index, it devolves to the address of the first element of the array. It follows that array elements are stored in consecutive memory locations.

#include <stdio.h>

int main(void){

char b;
int c;

//be sure
//pointer types are compatible
char *bPtr = &b;
int *cPtr = &c;

//increments by one

printf("%p\n", bPtr);
printf("%p\n", bPtr);
bPtr = bPtr + 1;
printf("%p\n", bPtr);

//increments by four

printf("%p\n", cPtr);
cPtr += 1;
printf("%p\n", cPtr);
printf("%p\n", ++cPtr);

return 0;

The int pointer in the example above is incremented by four, because the size of an int is (typically) four bytes. Likewise, the char pointer is incremented by one, because the size of a char is (almost always) one byte.

When one pointer is subtracted from another, we get the offset in units between the two pointers, not the difference in bytes.

#include <stdio.h>

int main(void){
    int ints[] = {15, 45, 60, 105};
    long long llInts[] = {1024, 16384, 65536};
    int *iP1 = ints;
    int *iP2 = ints + 1;
    long long *llPtr1 = &llInts[0];
    long long *llPtr2 = &llInts[1];
    printf("%p = %d\n", iP1, *iP1);
    printf("%p = %d\n", iP2, *iP2);
    printf("difference between two elements = %ld\n", iP2 - iP1);
    printf("\n%p = %lld\n", llPtr1, *llPtr1);
    printf("%p = %lld\n", llPtr2, *llPtr2);
    printf("difference between two elements = %ld\n", llPtr2 - llPtr1);
    return 0;

If you get the chance, take a look at my authors page at Amazon






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s