fork download
  1. #include <iostream>
  2.  
  3. typedef int ptr_t;
  4.  
  5. void *dereference(ptr_t what, int num)
  6. {
  7. ptr_t our_ptr = what;
  8. ptr_t *ptr = (ptr_t *)what;
  9.  
  10. ptr_t last, diff;
  11. last = what;
  12. for (int i = 0; i < num; i++) {
  13. // Grab the contents of the memory at our_ptr
  14. our_ptr = *ptr;
  15. // Set ptr to contents of memory at our_ptr
  16. ptr = (ptr_t *)our_ptr;
  17.  
  18. diff = (our_ptr - last);
  19. if ((i != 0)) { // diff comes out 16 for some reason
  20. std::cout << diff << '\n';
  21. }
  22. last = our_ptr;
  23. }
  24.  
  25.  
  26. return (void *)ptr;
  27. }
  28.  
  29. #include <cstdlib>
  30. int main() {
  31. int num_elements;
  32. if (std::cin >> num_elements) {
  33. ptr_t *pstr = (ptr_t *)malloc(num_elements * sizeof(ptr_t));
  34. for(int i=0; i<num_elements-1; ++i)
  35. pstr[i] = (ptr_t)(&pstr[i+1]);
  36. pstr[num_elements-1] = (ptr_t)NULL;
  37. ptr_t* r = (ptr_t*)dereference(pstr[0], num_elements-2);
  38. std::cout << (r - &pstr[0]);
  39. }
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 2860KB
stdin
100
stdout
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
99