0
#include <stdio.h>
int main (void) {

    int *a = (int *) 60;
    int *b = (int *) 40;
    printf("%lu\n", (a-b));
    printf("Integer Size = %lu\n", sizeof (int));
    printf("Pointer Size = %lu\n\n", sizeof (int *));

    char *c = (char *) 60;
    char *d = (char *) 40;
    printf("%lu\n", (c-d));
    printf("Character Size = %lu\n", sizeof (char));
    printf("Pointer   Size = %lu\n", sizeof (char *));

    return 0;
}

OUTPUT:

5
Integer Size = 4
Pointer Size = 8

20
Character Size = 1
Pointer   Size = 8

Please explain the output. What i am not able to understand is what int *a = (int *) 60; does ?

5
  • What are you confused about? What doesn't make sense? Why do you say there's a "glitch"? Commented Mar 29, 2016 at 2:46
  • It creates an integer pointer whose addess is 60. Commented Mar 29, 2016 at 2:47
  • 1
    What or who suggested l with "%lu\n", (a-b)? Commented Mar 29, 2016 at 2:48
  • Use printf("%td\n", (a - b)); Commented Mar 29, 2016 at 2:55
  • i was confused about that when pointer size is same i.e. 8 bytes then why two different answers for different data types. But now its clear from @Barmer's answer. Commented Mar 29, 2016 at 4:43

1 Answer 1

3
int *a = (int *)60;

declares a to be a pointer to an integer, and sets it to the memory location 60.

int *b = (int *)40;

declares b to be a pointer to an integer, and sets it to the memory location 40.

When you perform arithmetic on pointers, the arithmetic is done in units of the size of the data type that the integer points to. So

a - b

calculates the difference between a and b in terms of the number of integers between them. Since the size of an integer is 4 bytes, and the difference between the addresses is 20 bytes, the result is 20/4 = 5.

In the second block of code, since it uses char instead of int, the pointers point to 1-byte data, so subtracting the pointers is the same as subtracting their addresses.

In general, if you have two pointers

T *a;
T *b;

where T is any type, then

a - b

is equivalent to:

((char *)a - (char *)b)/sizeof(T)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.