c++ - sizeof returns wrong value if argument is passed via function -
this question has answer here:
let me ask question 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 receve 8
instead of 80
?
upd found similar question when function has specific-size array parameter, why replaced pointer?
you're taking size of char*
, not of array of 80 characters.
once it's decayed pointer, it's no longer seen array of 80 characters in testsizeof. it's seen normal char*
.
as possible reason why, consider code:
char* ch = new char[42]; testsizeof(ch, 42);
would expect sizeof magically work there?
Comments
Post a Comment