0

Let me ask my question by this test program:

#include <iostream>

void testSizeOf(char* buf, int expected) {
    std::cout << "buf sizeof " << sizeof(buf) << " expected " << expected << std::endl;
}


int main ()
{
    char buf[80];
    testSizeOf(buf, sizeof(buf));
    return 0;
}

Output:

 buf sizeof 8 expected 80

Why do I receve 8 instead of 80?

upd just found similar question When a function has a specific-size array parameter, why is it replaced with a pointer?

Community
  • 1
  • 1
Oleg Vazhnev
  • 23,239
  • 54
  • 171
  • 305

1 Answers1

4

You're taking the size of a char*, not of an array of 80 characters.

Once it's decayed to a pointer, it's no longer seen as an array of 80 characters in testSizeOf. It's seen just as a normal char*.

As for a possible reason why, consider this code:

char* ch = new char[42];
testSizeOf(ch, 42);

Would you expect sizeof to magically work there?

Corbin
  • 33,060
  • 6
  • 68
  • 78