Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. // Pointer Arithmetic
  6. // The following operations are valid with pointers:
  7. // ++, --, + (+=), - (-=)
  8.  
  9. int nums[10];
  10.  
  11. int i;
  12. // Getting length of nums using sizeof
  13. int len_sizeof = sizeof(nums) / sizeof(nums[0]);
  14.  
  15. for (i = 0; i < len_sizeof; i++)
  16. nums[i] = i;
  17.  
  18. int* ptr = nums;
  19.  
  20. for (i = 0; i < len_sizeof; i++, ptr++)
  21. printf("%d ", *ptr);
  22.  
  23. printf("\n");
  24.  
  25. // ptr currently points to the end of nums
  26. // To iterate through the array backwards
  27. // we can use the decrement operator.
  28. // NOTE: We have to decrement before
  29. // derefencing because we are outside of the array
  30. // and we need to move back into the array
  31. for (i = 0; i < len_sizeof; i++)
  32. printf("%d ", *(--ptr));
  33.  
  34. printf("\n");
  35.  
  36. // We have seen this already. The only difference
  37. // was we were dereferencing after the addition.
  38. int* index3 = nums + 3;
  39. int* index7 = nums + 7;
  40.  
  41. printf("The value at nums[3] is %d\n", *index3);
  42. printf("The value at nums[7] is %d\n", *index7);
  43.  
  44. int* ptrBegin = nums;
  45. int* ptrEnd = nums + len_sizeof;
  46.  
  47. // Using pointer subtraction to get the size of the nums array
  48. int len_ptrSubtract = ptrEnd - ptrBegin;
  49.  
  50. printf("nums contains %d ints\n", len_ptrSubtract);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement