0

I have a subclass of uiview and in it's initWithFrame: method I'm converting a nsarray to a float array like so:

NSArray *numbersArray = @[[NSNumber numberWithFloat:0.2], [NSNumber numberWithFloat:.8], [NSNumber numberWithFloat:.3], [NSNumber numberWithFloat:.6], [NSNumber numberWithFloat:.2]];

data = malloc(numbersArray.count * sizeof(float));
if (data == NULL) {
    // handle error
}
[numbersArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) {
    data[idx] = [number floatValue];
}];

//free(floatsArray);
for (int i = 0; i < sizeof (data) / sizeof (float); i++) {

    NSLog(@"float value found at %i => %f", i, data[i]);
}

If you run the code yourself, you'll see that it only returns 2 values from the array. What am I doing wrong here?

Larme
  • 24,190
  • 6
  • 51
  • 81
  • 2
    `sizeof(data)` does not return the size of the memory block. It gives you the size of the pointer. – rmaddy Oct 08 '15 at 16:29
  • Thank you! That did the trick. But how do I calculate the size of the float array then? I thought that was the way to do it.. – Daniel Ran Lehmann Oct 08 '15 at 16:33
  • 3
    You have to keep track it. In C, there is no way to get the size of an allocated memory block just from a pointer. – rmaddy Oct 08 '15 at 16:33
  • This is really a basic C question which has been covered many many times before. See http://stackoverflow.com/questions/2259890/using-sizeof-on-mallocd-memory for one example. – rmaddy Oct 08 '15 at 16:36

0 Answers0