0

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;  
}
Mike
  • 47,263
  • 29
  • 113
  • 177
  • Unless you're protecting some nuclear fusion trade secret, please do not use foo() and bar(). Also, you're passing an struct array to bar() so it does the implicit conversion for you. Welcome to SO! – Shark Mar 07 '13 at 17:22
  • 1
    Be aware that `MyStruct someStruct[]` in an argument list is not passing a MyStruct to the function, it is passing a _pointer_ to a MyStruct. – nos Mar 07 '13 at 17:24
  • However I think you can refactor to `bar(MyStruct &StructArray[])` and retain the sizeof size. – Shark Mar 07 '13 at 17:25
  • 1
    @Shark No, that just makes `bar` take a reference to a pointer instead of a copy of the pointer. You either need `void bar(MyStruct (&someStruct)[2])` (only accepts arrays containing 2 elements) or `template void bar(MyStruct (&someStruct)[N])` (accepts arrays of any size) – Praetorian Mar 07 '13 at 17:31

0 Answers0