ptr_ops.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // ptr_ops.c -- pointer operations
  2. #include <stdio.h>
  3. int main(void)
  4. {
  5. int urn[5] = {100,200,300,400,500};
  6. int * ptr1, * ptr2, *ptr3;
  7. ptr1 = urn; // assign an address to a pointer
  8. ptr2 = &urn[2]; // ditto
  9. // dereference a pointer and take
  10. // the address of a pointer
  11. printf("pointer value, dereferenced pointer, pointer address:\n");
  12. printf("ptr1 = %p, *ptr1 =%d, &ptr1 = %p\n",
  13. ptr1, *ptr1, &ptr1);
  14. // pointer addition
  15. ptr3 = ptr1 + 4;
  16. printf("\nadding an int to a pointer:\n");
  17. printf("ptr1 + 4 = %p, *(ptr4 + 3) = %d\n",
  18. ptr1 + 4, *(ptr1 + 3));
  19. ptr1++; // increment a pointer
  20. printf("\nvalues after ptr1++:\n");
  21. printf("ptr1 = %p, *ptr1 =%d, &ptr1 = %p\n",
  22. ptr1, *ptr1, &ptr1);
  23. ptr2--; // decrement a pointer
  24. printf("\nvalues after --ptr2:\n");
  25. printf("ptr2 = %p, *ptr2 = %d, &ptr2 = %p\n",
  26. ptr2, *ptr2, &ptr2);
  27. --ptr1; // restore to original value
  28. ++ptr2; // restore to original value
  29. printf("\nPointers reset to original values:\n");
  30. printf("ptr1 = %p, ptr2 = %p\n", ptr1, ptr2);
  31. // subtract one pointer from another
  32. printf("\nsubtracting one pointer from another:\n");
  33. printf("ptr2 = %p, ptr1 = %p, ptr2 - ptr1 = %td\n",
  34. ptr2, ptr1, ptr2 - ptr1);
  35. // subtract an integer from a pointer
  36. printf("\nsubtracting an int from a pointer:\n");
  37. printf("ptr3 = %p, ptr3 - 2 = %p\n",
  38. ptr3, ptr3 - 2);
  39. return 0;
  40. }