简体   繁体   中英

float arrays in objective C

Do I need to null-terminate a basic float array in objective C?

I have a basic float array:

float data[] = {0.5, 0.1, 1};

and when I do a sizeof(data) I get "12".

You don't need to null terminate it to create one, no. And in general a method taking a float[] would also take a size parameter to indicate how many elements there are.

You get sizeof(data) = 12 because a float is 4-bytes on your architecture and there's 3 of them.

sizeof return the amount of memory (in bytes) occupied by the parameter. In your case, every float occupies 4 bytes, thus 4*3=12.

As Hot Licks said in the comment of mattjgalloway's answer, there is not a standard way to retrieve the number of elements in a C array.

Using size = sizeof(data) / sizeof(float) works, but you must be careful in using this approach, since if you pass the array as a parameter it won't work.
A common approach is to store the size in a variable and use it as upper bound in your for loop (often functions that expect an array have an additional parameter to get the size of the array).

Using a null-terminated array is useful because you can iterate through your array and stop when the i -esim element is null (that's the approach of methods like strcmp ).

Values of type float can never be null, so it's not possible to terminate an array of type float with null. For one thing, variables of any primitive type always have a numeric value, and the various null constants (in Objective-C nil , Nil , NULL, and '\\0' ) have the literal value 0 , which is obviously a valid value in range of a float .

So even if you can compile the following line without a warning,

 float x = NULL;

...it would have the same consequence as this:

float x = 0;

Inserting a null constant in an array of type float would be indistinguishable from inserting 0.0 or any other constant zero value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM