C language: Use the realloc function to expand the memory size dynamically allocated by malloc or calloc.
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
Typedef struct
{
Char name [32];
Int age;
Char gender;
Float score [3];
} Student;
Typedef struct
{
Student * pData; // Student Information
Int size; // capacity
Int count; // number of current records
} Database;
// Initialize the database
Int initDatabase (Database * db );
// Destroy the database
Void destoryDatabase (Database * db );
// Insert a data entry
Int insertData (Database * db, Student stu );
// Print the database content
Void printDatabase (Database * db );
// Randomly generate data
Int myrandom (int range)
{
// Generate a random number in the range
Return rand () % range;
}
Int main ()
{
// Initialize Random Seed
Srand (unsigned) time (NULL ));
Database db;
// Initialize the database
If (initDatabase (& db )! = 0)
{
Printf ("database initialization failed! \ N ");
Return-1;
}
// Insert data in batches
For (int I = 0; I <20; I ++)
{
Student stu;
Sprintf (stu. name, "name % d", I );
Stu. age = myrandom (30 );
Stu. gender = myrandom (2 )? 'M': 'F ';
Stu. score [0] = myrandom (0, 100 );
Stu. score [1] = myrandom (100 );
Stu. score [2] = myrandom (100 );
If (insertData (& db, stu )! = 0)
{
Printf ("insertion failed! ");
Break;
}
}
// Print the database
PrintDatabase (& db );
// Destroy the database
DestoryDatabase (& db );
Return 0;
}
// Initialize the database
Int initDatabase (Database * db)
{
Db-> size = 10;
Db-> count = 0;
Db-> pData = (Student *) calloc (db-> size, sizeof (Student ));
Printf ("% p \ n", db-> pData );
If (db-> pData! = NULL)
{
Return 0;
}
Return-1;
}
// Destroy the database
Void destoryDatabase (Database * db)
{
Free (db-> pData );
Db-> pData = NULL;
}
// Insert a data entry
Int insertData (Database * db, Student stu)
{
// Determine whether the space is full before insertion
If (db-> count = db-> size) // if it is full, expand the space first.
{
Db-> size * = 22; // the new size is twice the original size.
// Use realloc to expand space
Db-> pData = (Student *) realloc (db-> pData, db-> size * sizeof (Student ));
Printf ("% p \ n", db-> pData );
If (db-> pData = NULL)
{
Return-1;
}
}
// Insert a new record
Db-> pData [db-> count] = stu;
Db-> count ++;
Return 0;
}
// Print the database content
Void printDatabase (Database * db)
{
Printf ("database size: % d, number of existing records: % d \ n", db-> size, db-> count );
Printf ("name, age, gender, mathematics, Chinese, English \ n ");
For (int I = 0; I <db-> count; I ++)
{
Printf ("% 8s \ t % 2d \ t % c \ t %. 2f \ t %. 2f \ t %. 2f \ t \ 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]);
}
}