我想保持我的錶行高的float []。我在這裏找到了一個很好的課程:http://forums.macnn.com/t/224809/nsmutablearray-vs-a-plain-c-array-for-storing-floats。從Objective-C調用C函數失去了價值
問題是,一旦C函數(位於另一個文件中)被調用,我傳入的float變爲0.每次都會發生這種情況,無論float值如何。
C函數:
typedef struct
{
float *array;
int count;
} floatArray;
BOOL AddFloatToArray (floatArray *farray, float newFloat)
{
if (farray->count > 0)
{
// The array is already allocated, just enlarge it by one
farray->array = realloc (farray->array, ((farray->count + 1) * sizeof (float)));
// If there was an error, return NO
if (farray->array == NULL)
return NO;
}
else
{
// Allocate new array with the capacity for one float
farray->array = (float *)malloc (sizeof (float));
// If there was an error, return NO
if (farray->array == NULL)
return NO;
}
printf("Adding float to array %f\n", newFloat);
farray->array[farray->count] = newFloat;
farray->count += 1;
printArrayContents(farray);
return YES;
}
int printArrayContents(floatArray* farray)
{
printf("Printing array contents\n");
for(int j=0; j < farray->count; j++)
printf("%f\n", farray->array[j]);
return 0;
}
從名爲:
NSDictionary* review = [self.reviews objectAtIndex:indexPath.row];
returnHeight = [ReviewCell cellHeightForReview:review];
NSLog(@"Adding height to array: %0.0f", returnHeight);
AddFloatToArray(heights, returnHeight);
這裏記錄的內容:
2012-09-28 11:46:12.787 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 101
Adding float to array 0.000000
Printing array contents
0.000000
2012-09-28 11:46:12.788 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 138
Adding float to array 0.000000
Printing array contents
0.000000
0.000000
2012-09-28 11:46:12.788 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 122
Adding float to array 0.000000
Printing array contents
0.000000
0.000000
0.000000
2012-09-28 11:46:12.789 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 139
Adding float to array 0.000000
Printing array contents
0.000000
0.000000
0.000000
我怎樣才能確保正確的價值實際上是插入浮動[]?
嘗試完全按照您發佈的代碼並使用'CGFloat returnHeight = 120.f; AddFloatToArray(heights,returnHeight);'和我的Xcode中的魅力一樣。當你在這裏c/p時,你確定你沒有從你的代碼中剝離任何東西嗎? – AliSoftware
一切都在這裏。可能值得一提的是C函數在不同的文件中。 – MishieMoo