1

Is there some way to pass an array as an object (as opposed to passing it as a pointer to its first element) and without using a structure? I want to be able to iterate through the array like this:

int get_max(int a[]){
    int max = 0;
    for(int i = 0; i < sizeof(a)/sizeof(a[0]); i++){
        if (a[i] > max) max = a[i];
    }
    return max;
}
user821
  • 110
  • 10
  • 3
    Are you aware of `std::array` or `std::vector`? If you cannot use either of those for some reason, then the canonical way to do this is to pass in both the array and the number of elements `int get_max(int a[], std::size_t count)` – Cory Kramer Jan 05 '20 at 13:30
  • 1
    `int a[]` as a function argument becomes `int *a`. So no. – rustyx Jan 05 '20 at 13:33
  • @CoryKramer I only want to pass the array, without passing another argument (such as its size). – user821 Jan 05 '20 at 13:33
  • 2
    @icecream2727 you can't. The information of size gets lost at the moment the array is passed to a function (and becomes an int* as rustyx mentioned), thus `sizeof` won't give you the size of the array. – user1810087 Jan 05 '20 at 13:42
  • @user1810087 I see. So ```sizeof(a)``` would be the size of the pointer to the first element in ```a```, and ```sizeof(a[0])``` would be the size of the first **integer** in ```a```. Right? – user821 Jan 05 '20 at 13:46
  • https://gcc.godbolt.org/z/qVDEjP – Aykhan Hagverdili Jan 05 '20 at 14:29

1 Answers1

4

For raw arrays, you can pass the array by reference to preserve the size information (which is lost in array-to-pointer decay), and make the function template for arbitrary length arrays. e.g.

template <size_t S>
int get_max(int (&a)[S]) {
    int max = std::numeric_limits<int>::min();
    for (size_t i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
    // or
    // for (size_t i = 0; i < S; i++) {
        if (a[i] > max) max = a[i];
    }
    return max;
}

LIVE

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • I've tried that on MSVC 15.9.15 with two arrays of different sizes (5 & 7 elements), compiling for release x64, and the compiler created two subroutines from the template, one for 5 elements, and another for 7. Somehow, I doubt this is the desired result in this case. – Uri Raz Jan 05 '20 at 13:56
  • @UriRaz Yes, see [template instantiation](https://en.cppreference.com/w/cpp/language/function_template#Function_template_instantiation). – songyuanyao Jan 05 '20 at 14:02
  • @songyuanyao : While this is a nice trick, it probably is worth mentioning that this could lead to code bloat, since every time `get_max` is called with a different array size, a new function is created. – user1810087 Jan 06 '20 at 08:40