我記得我從蘋果讀取文檔前一段時間說這樣的事情可以用類似結構天真地實現:
struct {
void *data; //other type rather than void is easier
int length;
} MyArray;
MyArray *MyArrayCreate(){
//mallocate memory
return ...
}
void MyArrayRelease(){
free(...);
}
和實施檢查數組和長度的函數沒有足夠長的時間,那麼將分配另一個足夠大的數組,之前的數據將被複制到它並添加新的數據。
MyArrayInsertAt(MyArray *array, index, void *object){
if (length < index){
//mallocate again, copy data
//update length
}
data[index] = object;
}
因此,它可以使用像這樣:
MyArray *array = MyArrayCreate();
MyArrayInsertAt(array, 5, something);
MyArrayRelease(array);
MyArrayInsertAt()函數不會贏得一個價格它的性能,但它可能是因爲沒有高要求苛刻的程序/應用
的解決方案
我只是找不到鏈接...也許有人也讀過它?
添加: 我發現GNU NSMutableArray(Objective-C)方法的實現是在C中完成的,它們與上面的一樣。每次需要添加對象時,它們都會將數組大小加倍,並且不適合數組。見行131到145
但std :: vector也是如此。 – helpermethod 2011-04-08 11:43:59
'std :: vector' in not C – pajton 2011-04-08 11:44:47