2021年2月5日星期五

Pointer and memory arithmetic in C

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 for ptrdiff_t, and %d for actual memory difference (wouldn't this just be an int or is there a better formatter for this?)
https://stackoverflow.com/questions/66073248/pointer-and-memory-arithmetic-in-c February 06, 2021 at 11:16AM

没有评论:

发表评论