0

I notice two different behaviors when invoking sizeof on primitive array that is not argument of function, and calling it on one that is argument of function.

Example:

I have array of six ints (in my codebase, it's much more than that). I am trying to write function that places those ints in std::vector<std::pair<std::pair<int, int>, int> >, which means the function must check that the size of the array it's given is multiple of three, before constructing the vector. I test sizeof a / sizeof a[0], right after declaring the int array, and it correctly returns 6. However, when I do:

#include <iostream>

using namespace std;

void doSomething(const int* a)
{
    cout << sizeof a / sizeof a[0] << endl;
    // do some real work down here
}

int main()
{

    int a[] = {40,30,60,38,609,780};
    doSomething(a);
}

it does not return 6. Why is this happening and what is the quickest and dirtiest way around this unexpected behavior?

Mike Warren
  • 3,796
  • 5
  • 47
  • 99
  • 2
    This behavior is very not unexpected. It is giving you the size of a pointer. Take a look at your function. Is that a pointer or is that an array? – DeiDei Nov 02 '16 at 00:17
  • Even if I change the function signature to `void doSomething(const int a[])`, it does the same thing. – Mike Warren Nov 02 '16 at 00:20
  • That is because the two are equivalent and mean exactly the same thing. Pass the size of the array as a second parameter. That's the popular practice. – DeiDei Nov 02 '16 at 00:23
  • @DeiDei "popular practice" is to use `std::vector` or `std::array` instead of a raw array. – Remy Lebeau Nov 02 '16 at 00:50
  • @RemyLebeau My bad, for some reason I thought this was tagged as C, not C++. Even then, the right thing to do is often not the popular practice. ;) – DeiDei Nov 02 '16 at 03:03

0 Answers0