我有一個結構CGPoint的c數組。當另一個CGPoint被添加時,我需要替換這個數組。我發誓我正在做這件事,它似乎很好,但最終我會得到一個EXC_BAD_ACCESS
。我錯過了什麼?EXC_BAD_ACCESS在結構中傳遞指針指針時?
下面是結構,我已經截斷刪除了許多不屬於的項目。
typedef struct{
CGPoint **focalPoints;
NSUInteger focalPointCount;
CGRect boundingRect;
}FocalPoints;
以下是我初始化:
CGPoint *fPoints = (CGPoint *)malloc(sizeof(CGPoint));
FocalPoints focalInfo = {&fPoints, 0, rect};
注意focalInfo
通過引用傳遞給另一個函數,就像這樣:anotherFunction(&focalInfo)
。
現在,這裏的該用新的替換點陣列的功能:
void AddFocalPoint (CGPoint focalPoint, FocalPoints *focal){
if (focalPoint.x == CGFLOAT_MAX) return;
if (!CGRectContainsPoint(focal->boundingRect, focalPoint)) return;
int origCount = focal->focalPointCount;
int newCount = origCount + 1;
CGPoint *newPoints = (CGPoint *) malloc((newCount) * sizeof(CGPoint));
for (int i = 0; i < newCount; i++)
newPoints[i] = (i < origCount) ? *focal->focalPoints[i] : focalPoint; //error occurs here
free(*focal->focalPoints);
*focal->focalPoints = newPoints;
focal->focalPointCount = newCount;
}
在第8行上述代碼時出現錯誤EXC_BAD_ACCESS:newPoints[i] = (i < origCount) ? *focal->focalPoints[i] : focalPoint;
。那麼我究竟做錯了什麼?
我不知道全部,但我認爲newPoints [i]是一個CGPoint,而* focal-> focalPoints [i]是一個CGPoint指針... – FrankieTheKneeMan 2012-03-19 20:45:42
你有沒有考慮使用鏈表,甚至'NSMutableArray' /'NSValue',這樣你就不會在每次添加一個點時分配,複製和釋放整個東西? – 2012-03-19 20:49:40
fPoints的原始malloc未在技術上使用。但是我分配空間是因爲AddFocalPoint函數會自由調用它,並且我不想釋放未被malloc'd的空間。 '&fPoints'爲fPoints添加一個額外的指針。我這樣做是因爲我相信這是取代c-array的唯一方法。 – 2012-03-19 20:49:43