Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 1st, 2012  |  syntax: None  |  size: 1.20 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. difference between pointer and reference in c?
  2. address    01   02   03
  3.              +----+----+----+...
  4. data within  | 23 | 6f | 4a |
  5.              +----+----+----+...
  6.        
  7. char c = 'z';  // 'z' is 7a in hex
  8.        
  9. address    01   02   03
  10.              +----+----+----+...
  11. data within  | 7a | 6f | 4a |
  12.              +----+----+----+...
  13.        
  14. char* p = &c;  // point at c
  15.        
  16. address    01   02   03
  17.              +----+----+----+...
  18. data within  | 7a | 01 | 4a |
  19.              +----+----+----+...
  20.        
  21. char& r = c;
  22.        
  23. const char& r = c;
  24. r = 'y';  // error; you may not change c through r
  25. c = 'y'   // ok. and now r == 'y' as well
  26.        
  27. | Address  | Value          |
  28. |----------|----------------|
  29. |0x1111    |0x1112          | <-- Pointer!
  30. |0x1112    |42              | <-- Pointed value
  31. |0x1113    |42              | <-- Some other value
  32.        
  33. mov rax, [r8]
  34.        
  35. void add(int* x)
  36. {
  37.     *x = *x + 7;
  38. }
  39.        
  40. void cppadd(int& x)
  41. {
  42.     int a = 7;
  43.     x = &a; // doesn't work.
  44. }
  45.        
  46. int a;
  47. int* b = &a;
  48. // b holds the memory address of a, not the value of a.
  49.        
  50. int a;
  51. int* b = &a;
  52. // b is a reference to a.
  53.        
  54. int a;
  55. int* b = &a;
  56. int c = *b;
  57. // c dereferences b, meaning that c will be set with the value stored in the address that b contains.