LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

for dynamically allocated double arrays, sizeof() does not work

Solved!
Go to solution

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.

 

0 Kudos
Message 1 of 5
(3,554 Views)
Solution
Accepted by topic author TurboMetrologist

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.

0 Kudos
Message 2 of 5
(3,548 Views)

Approximately 95% of the effort of implementing the C99 upgrades in CVI was devoted to implementing variable length arrays Smiley Tongue

 

Luis

NI

Message 3 of 5
(3,523 Views)

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.

 

 

 

 

0 Kudos
Message 4 of 5
(3,520 Views)

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. Smiley Wink

 

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

0 Kudos
Message 5 of 5
(3,514 Views)