Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int main()
- {
- // Pointer Arithmetic
- // The following operations are valid with pointers:
- // ++, --, + (+=), - (-=)
- int nums[10];
- int i;
- // Getting length of nums using sizeof
- int len_sizeof = sizeof(nums) / sizeof(nums[0]);
- for (i = 0; i < len_sizeof; i++)
- nums[i] = i;
- int* ptr = nums;
- for (i = 0; i < len_sizeof; i++, ptr++)
- printf("%d ", *ptr);
- printf("\n");
- // ptr currently points to the end of nums
- // To iterate through the array backwards
- // we can use the decrement operator.
- // NOTE: We have to decrement before
- // derefencing because we are outside of the array
- // and we need to move back into the array
- for (i = 0; i < len_sizeof; i++)
- printf("%d ", *(--ptr));
- printf("\n");
- // We have seen this already. The only difference
- // was we were dereferencing after the addition.
- int* index3 = nums + 3;
- int* index7 = nums + 7;
- printf("The value at nums[3] is %d\n", *index3);
- printf("The value at nums[7] is %d\n", *index7);
- int* ptrBegin = nums;
- int* ptrEnd = nums + len_sizeof;
- // Using pointer subtraction to get the size of the nums array
- int len_ptrSubtract = ptrEnd - ptrBegin;
- printf("nums contains %d ints\n", len_ptrSubtract);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement