Advertisement
junghu1124

Untitled

Sep 22nd, 2023
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int& foo() {
  4.     int a = 10;
  5.     return a;
  6. }
  7.  
  8. void decay_to_pointer(int arr[3]) {
  9.     std::cout << "array decays to pointer: " << sizeof(arr) << std::endl;
  10. }
  11.  
  12. void pass_by_reference(int (&arr)[3]) {
  13.     std::cout << "array passed to function by reference: " << sizeof(arr) << std::endl;
  14. }
  15.  
  16. int main() {
  17.     int b = 10;
  18.     double c = 4.5;
  19.  
  20.     double* dptr;
  21.     // dptr = &b // compile error
  22.     dptr = reinterpret_cast<double*>(&b);
  23.     std::cout << "before b: " << b << std::endl;
  24.     std::cout << "before *dptr: " << *dptr << std::endl; // 이상한 주소를 가리키게 됨
  25.     *dptr += 1;
  26.     std::cout << "before b: " << b << std::endl;
  27.     std::cout << "before *dptr: " << *dptr << std::endl;
  28.  
  29.     std::cout << std::endl;
  30.  
  31.     int* iptr;
  32.     // iptr = &c; // compile error
  33.     iptr = reinterpret_cast<int*>(&c);
  34.     std::cout << "before c: " << c << std::endl;
  35.     std::cout << "before iptr: " << *iptr << std::endl; // 이상한 주소를 가리키게 됨
  36.     *iptr += 2;
  37.     std::cout << "before c: " << c << std::endl;
  38.     std::cout << "before iptr: " << *iptr << std::endl;
  39.     std::cout << std::endl;
  40.  
  41.     int* dang_p;
  42.     // int* dang_p = 10; // rvalue assign -> compile error
  43.     // *dang_p = 10; // runtime error
  44.     int& dang_r = foo();
  45.  
  46.     // std::cout << *dang_p << std::endl; // runtime error
  47.     // std::cout << dang_r << std::endl; // runtime error
  48.  
  49.     int arr[3] = {0,};
  50.     decay_to_pointer(arr);
  51.     pass_by_reference(arr);
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement