08-08-2011 01:53 PM
For a typical double array, if you need to get the size, you would use
numElems=(sizeof(myArray)/sizeof(myArray[0]));
However, for dynamically allocated double arrays (see here for example) this no longer works.
For the example above, sizeof(myArray) returns 4, and sizeof(myArray[0]) returns 8.
Solved! Go to Solution.
08-08-2011 05:14 PM
That's because sizeof(myArray) is the size of the pointer to the dynamically allocated array.
sizeof(myArray[0]) is the size of a double (8 bytes).
If you know the size you malloc'd then just use this instead of the sizeof(myArray) function.
Array size (for use in bounds checking for example) is a compile-time thing in C89 (though CVI will hack in run-time bounds checking for you in a debug compile). So even if you cast a malloc'd buffer pointer to an array type, the compiler's out of the picture at run time when the buffer gets established to a (potentially) run-time determined size, so it can't help you. More modern languages (e.g. Java, C#) all get around this problem. C99 allows variable length arrays to be declared but I'm not sure NI implemented this in their C99 upgrades.
08-10-2011 04:26 PM
Approximately 95% of the effort of implementing the C99 upgrades in CVI was devoted to implementing variable length arrays
Luis
NI
08-10-2011 04:45 PM
Luis -
kudos, "attaboys", thank you's are all in order for you and the NI CVI team. 16 byte alignment support, variable length arrays - you guys are working off the list of improvements for sure. I appreciate that it must have been a lot of work to get the variable length arrays implemented, having done compiler internals myself years ago.
So how does sizeof () work for a variable length array? The H&S reference book I have doesn't really make it clear what happens if you call sizeof on a variable length array in C99. I can see how it might not work - C99 doesn't add any functions or semantics to the variable length arrays to help you figure out their size.
08-10-2011 06:48 PM
You're welcome! You should actually thank Mert when he pops again in the forum. He's the one who did all that dirty work.
sizeof works for variable-length arrays because variable-length arrays are allocated on the stack, like other local arrays, and the compiler can generate assembly code for the sizeof expression that calculates the stack offsets of the array based on the expression used to declare the array.
Luis