Advertisement
Radfler

static arrays vs dynamic arrays

May 10th, 2015
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <new>
  3.  
  4. using namespace std;
  5.  
  6. template<typename Type, size_t Size>
  7. void print_size(Type (&array)[Size]) {
  8.     cout << "size of array: " << Size << '\n';
  9. }
  10.  
  11. int main() {
  12.  
  13.     int static_array[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
  14.     int* dynamic_array = new int[10]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  15.  
  16.     for(int e : static_array) {
  17.         cout << e << ' ';
  18.     }
  19.     cout << '\n';
  20.  
  21.     // using range-for loop is impossible on dynamic arrays (http://bit.ly/1gBhmPF)
  22.     // for(int e : dynamic_array) {
  23.     //  cout << e << '\t';
  24.     // }
  25.  
  26.     print_size(static_array);
  27.  
  28.     // type of dynamic_array is not array (std::is_array<decltype(dynamic_array)>::value == false)
  29.     // print_size(dynamic_array);
  30.  
  31.     // sizeof array
  32.     cout << "sizeof static array: " << sizeof static_array << '\n';
  33.  
  34.     // sizeof pointer
  35.     cout << "sizeof dynamic array: " << sizeof dynamic_array << '\n';
  36.  
  37.     delete[] dynamic_array;
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement