I have a dynamically allocated array of structs (myStructArray
). In order to get the number of elements in it, as we know (even though a hack), I do a (sizeof(myStructArray)/sizeof(myStructArray[0]
) which works as expected.
However, when I pass myStructArray
into a function, performing the sizeof
on that struct array parameter (someStructArray
) gives me what I want directly - the number of array elements.
why???
I know myStructArray
is being passed by reference, and as validation and sanity, I manipulated the elements of someStructArray
inside of bar()
and it did change the contents of myStructArray
. So, this one is bothering me.
Sure, I like that I can get the number of array elements inside bar()
without doing a (sizeof(someStructArray)/sizeof(someStructArray[0])
) hack, but I won't be comfortable/confident that it will always resolve this way unless I understand why. Thanks!
typedef struct {
int a;
int b;
} MyStruct;
...
.h file
class MyClass {
public:
static MyStruct myStructArray[];
};
.cpp file
MyClass::myStruct[] =
{{1,2}, {3,4}};
void MyClass::foo() {
sizeof(myStruct); // 16 (elements x size of element)
cout << myStruct[0].a; // 1
bar(myStruct);
cout << myStruct[0].a; // 17
}
...
void bar(MyStruct someStruct[]) {
sizeof(someStruct); // 2 (just elements??) why different???
someStruct[0].a = 17;
}