Guest User

Untitled

a guest
Jun 20th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. // A pointer saves the physical address of a value
  5. int a = 1; // Declaring integer variables and saving integers to the variables
  6. int b = 2;
  7. int pointerMath;
  8.  
  9. // Declaring integer pointers but not pointing to any addresses just yet
  10. int *x;
  11. int *y;
  12.  
  13. // Saving an integer pointer to the address of an integer variable
  14. x = &a; // Remember that using an `&` means it's an address
  15. y = &b;
  16.  
  17. /*
  18. x = a will compile, but it will provide a warning and makes utlizing the
  19. pointer for math later, impossible. This is because we aren't specifying
  20. that we're creating a pointer, by directly looking for an address with `&`.
  21. */
  22.  
  23. printf("Pointer x output looking for a POINTER -> %p\n", x); // -> [Address]
  24. printf("Pointer x output looking for an INT -> %d\n", x); // -> [Address] WARNING
  25. printf("Pointer x output looking for an INT -> %d\n", *x); // -> 1 (value)
  26. /* What is the meaning of this?! ^
  27. Without the asterisk we get a memory address
  28. With an asterisk we get the value at that address
  29. */
  30.  
  31. // Using the values stored at the addresses contained in the pointers
  32. pointerMath = *x + *y;
  33. printf("Adding two pointers -> %d\n", pointerMath); // -> 3
  34.  
  35. // Can we change the value stored within a pointer?
  36. *x = 10;
  37. printf("Changing the value of pointer x -> %d\n", *x); // -> 10 YES
  38.  
  39. return 0;
  40.  
  41. /* Take Away
  42. Pointers are just like any variable. The main difference is that they store
  43. the address of a variable rather than it's direct value.
  44.  
  45. This means that no matter the scope of our program, we have a stored reference to something that
  46. lives at a particular place. We can still modify or view that value, or if we so choose, simply
  47. view the address of whatever lives there.
  48. */
  49. }
Add Comment
Please, Sign In to add comment