user1574598
user1574598

Reputation: 3881

Integer Pointer Subtraction

I've written a few lines of code predominantly from a book that gets you to declare an integer array, then subtract and pass two addresses from the array to another integer, in order to pass into a printf statement. I'm not sure why, but my actual pointers: aPointer and bPointer seem to be 8 bytes, which poses a problem when I try and pass the subtracted addresses to an integer.

I then changed the latter to a long. The errors are not present in Xcode now, but I cannot print the address of pointerSubtraction properly using the %p specifier which does indeed expect an int and not a long.

    int arrayOfInts[10];

            for (int i = 0; i < 10; i++) {
                arrayOfInts[i] = i;
                printf("%d", arrayOfInts[i]);
                // prints out 0123456789
            }

            printf("\n");

            int *aPointer = &arrayOfInts[1];  // get address of index 1
            int *bPointer = &arrayOfInts[7];  // get address of index 7
            long pointerSubtraction = bPointer - aPointer;  // subtract index 7 with 1

            printf("The size of aPointer is %zu bytes \n", sizeof(aPointer));
            printf("The size of aPointer is %zu bytes \n", sizeof(bPointer));
            printf("The address of aPointer is %p \n", aPointer);
            printf("The address of bPointer is %p \n", bPointer);
            printf("The address of final is %p \n", pointerSubtraction);
            printf("The value of pointerSubtraction is %ld \n \n", pointerSubtraction);

Upvotes: 3

Views: 683

Answers (2)

alk
alk

Reputation: 70893

You might like to use a variable typed ptrdiff_t to store the difference of two pointer values, two addresses.

To printf() out a ptrdiff_t use the length modifier "t". As ptrdiff_t is a signed integer use the conversion specifier "d".

#include <stddef.h>
#include <stdio.h>

int main(void)
{
  int a = 0;
  int b = 0, * pa = &a;

  ptrdiff_t ptr_diff = pa - &b;

  printf("pd = %td\n", ptr_diff);

  return 0;
}

Also the conversion specifier "p" is only defined for pointers to void. So the printf() calls shall look like:

      printf("The address of aPointer is %p \n", (void *) aPointer);
      printf("The address of bPointer is %p \n", (void *) bPointer);

Also^2 : The result of adding or substrating a value v from a pointer p is only a valid address if the result pv of the operation still refers to (an element/member of) the object the original pointer p pointed to.

Upvotes: 2

Neptune
Neptune

Reputation: 627

In your code aPointer is the value pointed by *aPointer. Same thing for bPointer.

As the comment says pointerSubtraction is the value obtained by the subtraction, not the address.

Upvotes: 1

Related Questions