1
template <typename list_type>
int len(list_type list) {

    std::cout << sizeof(list);

    return (sizeof(list) / sizeof(list[1]));
}


int main() {

    int list[5] = {1, 2 ,3 ,5 ,4};

    std::cout << sizeof(list) << "\n";
    len(list);
}

When I run the program I get: 20 then 4. Why is there a difference when though it's the same list?

TCG
  • 121
  • 13

1 Answers1

1

The array decayed to a pointer.

list is an int* in len() and int[5] in main.

As mentioned here there are two possible fixes:

  • Use a reference
  • Explicitly use a reference to array type

If you use a reference then it will work (the pointer does not decay), but you would still have to calculate the number of elements:

#include <iostream>

template <typename list_type>
int len(list_type &list) {
    std::cout << sizeof(list) << '\n';
    return (sizeof(list) / sizeof(list[1]));
}

int main() {
    int list[5] = {1, 2 ,3 ,5 ,4};
    std::cout << sizeof(list) << "\n";
    auto element_count = len(list);
    std::cout << "There are " << element_count << " elements in the list.\n";
}

For the second option, you get the size of the array at compile time:

#include <iostream>

template <typename list_type, size_t N>
int len(list_type (&list) [N]) {
    std::cout << sizeof(list) << '\n';
    return N;
}

int main() {
    int list[5] = {1, 2 ,3 ,5 ,4};
    std::cout << sizeof(list) << "\n";
    auto element_count = len(list);
    std::cout << "There are " << element_count << " elements in the list.\n";
}
Community
  • 1
  • 1
wally
  • 10,717
  • 5
  • 39
  • 72
  • Ah, so how do I get it to be the same? – TCG Dec 09 '16 at 21:30
  • 1
    See [here](http://stackoverflow.com/questions/16505376/how-to-pass-array-to-function-template-with-reference). – wally Dec 09 '16 at 21:32
  • I just did `int len(list_type &list) {` and it worked, thanks – TCG Dec 09 '16 at 21:36
  • 1
    @TCG, Yes, good point, seems [there is an answer](http://stackoverflow.com/a/1863767/1460794) for this already. – wally Dec 09 '16 at 21:37
  • So should I just delete this question? – TCG Dec 09 '16 at 21:38
  • 1
    @TCG Up to you, the answer I linked to already knew it was pointer decay. Your question is asking about the reason for a different size. I wouldn't be surprised if the size question was also asked before. If we can find a matching duplicate then we can flag the question, or you can delete. It's your question. ;) – wally Dec 09 '16 at 21:41