Skip to main content

Command Palette

Search for a command to run...

Pointer Subtraction

Published
•1 min read•View as Markdown

The formula used by pointer substraction is:

( q - p ) == ( addr( q ) - addr( p ) ) / sizeof( T )

with T being the type of both p and q.

int array[10]; 
int* p1 = array + 2; 
int* p2 = array + 5;

ptrdiff_t a = p2 - p1; // 3
ptrdiff_t b = p1 - p2; // -3

You can make sense of p-q only if p and q point to the same array/one past the last element of the same array.

Strictly speaking, the pointer difference is of type ptrdiff_t and you should use the format specifier %td for printing the difference. But the program works fine even if you use int variable to store the pointer difference.

22 views

More from this blog

P

Programming Tutorials

89 posts