Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some pointer clarification [duplicate]

Tags:

c

pointers

Possible Duplicate:
C question with pointers

I need some help with pointers, specifically the following example:

#include <stdio.h>
int main()
{
    int *i, *j;

    i = (int *) 60;
    j = (int *) 40;
    printf("%d", i - j);

    return 0;
}

This code generates 10 as output. I just need to know what exactly i - j does here.

like image 770
user1571753 Avatar asked May 14 '26 09:05

user1571753


2 Answers

i and j point to memory locations 60 and 40, respectively.

What you're doing here is pointer subtraction. If i and j were byte pointers (char *), i-j would be 20, as one might expect.

However, with other pointers, it returns the number of elements between the two pointers. On most systems, (int *)60 - (int *)40 would be 5, as there is room for five 4-byte integers in those twenty bytes. Apparently, your platform has 16 bit integers.

like image 64
Max Avatar answered May 15 '26 21:05

Max


The program is probably supposed to print the pointer difference between 60 and 40, cast to pointer to int. The pointer difference is the number of ints that would fit in the array from address 40 to address 60 (exclusive).

That said, the program violates the C standard. Pointer arithmetic is undefined except with pointers pointing into the same (static, automatic or malloc'd) array, and you cannot reliably print a pointer difference with %d (use %td instead).

like image 45
Fred Foo Avatar answered May 15 '26 23:05

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!