Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 993
Ayrad Avatar asked Jun 04 '26 19:06

Ayrad


2 Answers

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.

like image 135
mattjgalloway Avatar answered Jun 07 '26 13:06

mattjgalloway


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).

like image 43
Manlio Avatar answered Jun 07 '26 12:06

Manlio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!