fork download
  1. #include <iostream>
  2. #include <type_traits>
  3.  
  4. // Array for reference. Unused except for grabbing type.
  5. int array[5];
  6.  
  7. // Array's type. Type is: int (*)[5]
  8. using A = decltype(array);
  9.  
  10. // Function that takes pointer-to-array as argument.
  11. // Should use templates, really, or a typedef if array definition will never change.
  12. int sum(int (*arr)[5]) {
  13. int ret = 0;
  14. for (int i = 0; i < 5; i++) { ret += (*arr)[i]; }
  15. return ret;
  16. }
  17.  
  18. // Function that takes reference-to-array as argument.
  19. // Should use templates, really, or a typedef if array definition will never change.
  20. int refsum(int (&arr)[5]) { return sum(&arr); }
  21.  
  22. // It's not that much cleaner, but templates help a lot here.
  23. template<typename T, size_t N, typename TN = T[N]>
  24. int temsum(T (*arr)[N]) {
  25. static_assert(std::is_same<T, int>::value && (N == 5));
  26. static_assert(std::is_same<TN*, A*>::value);
  27. return sum(arr);
  28. }
  29.  
  30. // Function that returns pointer-to-array.
  31. // Looks awful.
  32. int (*create())[5] {
  33. // Don't do this outside of throwaway examples. ^_^
  34. int (*arr)[5] = reinterpret_cast<int(*)[5]>(new int[5]);
  35. for (int i = 1; i < 6; i++) { (*arr)[i - 1] = i * i; }
  36. return arr;
  37. }
  38.  
  39. // This is the only sane way to work with pointers-to-array, since a typedef uses normal syntax.
  40. void destroy(A* arr) {
  41. // Don't do this, either.
  42. delete[] reinterpret_cast<int*>(arr);
  43. }
  44.  
  45. int main() {
  46. // Clean way to use pointer-to-array: Use the typedef.
  47. A* arr = create();
  48. int sum1 = sum(arr);
  49. int sum2 = refsum(*arr);
  50. int sum3 = temsum(arr);
  51.  
  52. std::cout << sum1 << ' ' << sum2 << ' ' << sum3 << '\n';
  53.  
  54. destroy(arr);
  55. }
Success #stdin #stdout 0s 5400KB
stdin
Standard input is empty
stdout
55 55 55