Taking the following program:
#include <stdio.h> #include <stddef.h> int main(void) { int *a = &(int) {4}; ptrdiff_t b = (a+1) - a; int c = (char*) (a+1) - (char*) a; // actual memory difference printf("The first memory address is at: %p and the one after is: %p\n" "The difference with pointer arithmetic is: %td\n" "And actual difference in memory address is: %d\n", a, a+1, b, c); }
The first memory address is at: 0x7fff9cb3a1e0 and the one after is: 0x7fff9cb3a1e4
The difference with pointer arithmetic is: 1
And actual difference in memory address is: 4
Is this the proper way to do:
- ptr arithmetic:
ptrdiff_t b = (a+1) - a;
- actual arithmetic between memory addresses:
(char*) (a+1) - (char*) a;
- Formatters:
%td
forptrdiff_t
, and%d
for actual memory difference (wouldn't this just be an int or is there a better formatter for this?)
没有评论:
发表评论