`realloc` 可調整 `malloc`/`calloc` 分配的記憶體區塊大小,常用於實作動態陣列 (如 C++ `vector` 底層)。本文以學生資料庫為例,示範容量不足時倍增擴容的完整流程。
typedef struct {
char name[32];
int age;
char gender;
float score[3];
} Student;
typedef struct {
Student *pData; /* 動態陣列基址 */
int size; /* 當前容量 (元素數) */
int count; /* 實際元素數 */
} Database;
int initDatabase(Database *db) {
db->size = 10;
db->count = 0;
db->pData = (Student *)calloc(db->size, sizeof(Student));
printf("Initial addr: %p\n", db->pData);
return db->pData ? 0 : -1;
}
void destroyDatabase(Database *db) {
free(db->pData);
db->pData = NULL; /* 防止野指標 */
}
int insertData(Database *db, Student stu) {
if (db->count == db->size) { /* 容量已滿 */
db->size *= 2; /* 倍增策略 */
Student *newPtr = (Student *)realloc(db->pData, db->size * sizeof(Student));
printf("Realloc addr: %p\n", newPtr);
if (!newPtr) return -1; /* 擴容失敗 */
db->pData = newPtr;
}
db->pData[db->count++] = stu; /* 放入新元素 */
return 0;
}
void printDatabase(Database *db) {
printf("Size: %d, Count: %d\n", db->size, db->count);
printf("%-8s %3s %2s %6s %6s %6s\n", "Name", "Age", "G", "Math", "Lang", "Eng");
for (int i = 0; i < db->count; i++) {
printf("%-8s %3d %2c %6.2f %6.2f %6.2f\n",
db->pData[i].name, db->pData[i].age, db->pData[i].gender,
db->pData[i].score[0], db->pData[i].score[1], db->pData[i].score[2]);
}
}
int main() {
srand((unsigned)time(NULL));
Database db;
if (initDatabase(&db) != 0) return -1;
for (int i = 0; i < 20; i++) {
Student s;
sprintf(s.name, "name%d", i);
s.age = rand() % 30;
s.gender = (rand() % 2) ? 'M' : 'F';
s.score[0] = rand() % 100;
s.score[1] = rand() % 100;
s.score[2] = rand() % 100;
if (insertData(&db, s) != 0) break;
}
printDatabase(&db);
destroyDatabase(&db);
return 0;
}
掌握 `malloc`/`calloc`/`realloc`/`free` 四大函數與倍增擴容模式,即可實作高效、安全的動態陣列資料結構。