测试用例

This commit is contained in:
2026-08-29 11:39:28 +08:00
parent a0758766c5
commit 8fd65b0de0
19 changed files with 1723 additions and 432 deletions
+26 -9
View File
@@ -4,7 +4,8 @@
/* ------------------------------------------------------------------------------------------------------------------ */
/* */
#define DEFAULT_INITIAL_CAPACITY 4
#define DEFAULT_INITIAL_CAPACITY 4
#define MIN_SHRINK_CAPACITY 4
/* ------------------------------------------------------------------------------------------------------------------ */
/* */
@@ -13,14 +14,17 @@ c_err_t c_ArrayList_Init(c_ArrayList_t* self, c_size_t obj_size, c_size_t capaci
if (!self || obj_size == 0) return C_ERR_PARAM;
self->obj_size = (int)obj_size;
self->capacity = (capacity > 0) ? capacity : DEFAULT_INITIAL_CAPACITY;
self->size = 0;
self->capacity = capacity;
// 分配連續記憶體空間:容量 * 單個物件大小
self->array = C_ALLOC(self->capacity * self->obj_size);
if (!self->array) {
self->capacity = 0;
return C_ERR_NOMEM;
if (capacity==0) {
self->array = NULL;
}else {
self->array = C_ALLOC(self->capacity * self->obj_size);
if (!self->array) {
self->capacity = 0;
return C_ERR_NOMEM;
}
}
return C_ERR_OK;
@@ -35,11 +39,11 @@ void c_ArrayList_Destroy(c_ArrayList_t* self) {
}
c_err_t c_ArrayList_Add(c_ArrayList_t* self, void* obj) {
if (!self || !self->array || !obj) return C_ERR_PARAM;
if (!self || !obj) return C_ERR_PARAM;
// 動態擴容邏輯
if (self->size >= self->capacity) {
const c_size_t new_capacity = self->capacity<<1;
const c_size_t new_capacity = (self->capacity==0)?DEFAULT_INITIAL_CAPACITY:(self->capacity<<1);
void* new_array = C_REALLOC(self->array, new_capacity * self->obj_size);
if (!new_array) {
return C_ERR_NOMEM;
@@ -79,6 +83,19 @@ c_err_t c_ArrayList_Remove(c_ArrayList_t* self, c_size_t index) {
}
self->size--;
// 策略:当实际大小少于等于容量的 1/4,且缩容后的容量不低于设定的最小阈值时触发
if (self->size > 0 && self->size <= (self->capacity >> 2)) {
c_size_t new_capacity = self->capacity >> 1; // 容量减半
void* new_array = C_REALLOC(self->array, new_capacity * self->obj_size);
if (new_array) { // 如果 realloc 失败不影响原有数据安全,这里采用安全赋值
self->array = new_array;
self->capacity = new_capacity;
}
}
return C_ERR_OK;
}