my_table.h
#ifndef MY_GLOB_HEAD
#define MY_GLOB_HEAD
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN_SMALL 100
#define LEN_NORMAL 1000
#define LEN_BIG 10000
typedef struct my_row
{
long id;
char name[LEN_SMALL];
int score;
void *pointer;
} t_my_row;
typedef struct my_table
{
int size;
int curr;
t_my_row *array;
} t_my_table;
t_my_table table_create(int size);
void table_extend(t_my_table *table, int addsize);
void table_insert(t_my_table *table, t_my_row *new_row);
void table_print(t_my_table *table);
#endif
my_table.c
#include "my_table.h"
t_my_table table_create(int size)
{
t_my_row *rows = (t_my_row *)calloc(size, sizeof(t_my_row));
t_my_table table;
table.size = size;
table.curr = -1;
table.array = rows;
return table;
}
void table_extend(t_my_table *table, int addsize)
{
int newsize = (addsize + table->size) * sizeof(t_my_row);
t_my_row *rows = (t_my_row *)realloc(table->array, newsize);
if (rows == NULL)
{
fprintf(stderr, "Error - unable to allocate required memory\n");
exit(-1);
}
table->size += addsize;
table->array = rows;
}
void table_insert(t_my_table *table, t_my_row *new_row)
{
if (table->curr == table->size - 1)
{
table_extend(table, table->size);
}
table->curr++;
table->array[table->curr].id = new_row->id;
strcpy(table->array[table->curr].name, new_row->name);
table->array[table->curr].score = new_row->score;
table->array[table->curr].pointer = new_row->pointer;
}
void table_print(t_my_table *table)
{
int i;
for (i = 0; i <= table->curr; i++)
{
printf("%ld | ", table->array[i].id);
printf("%s | ", table->array[i].name);
printf("%d | ", table->array[i].score);
printf("%p | \n", table->array[i].pointer);
}
}
main.c
#include "my_table.h"
int main()
{
t_my_row newrow;
newrow.id = 123;
strcpy(newrow.name, "aaa");
newrow.score = 666;
newrow.pointer = NULL;
t_my_table table = table_create(2);
int i;
for (i = 1; i <= 1000000; i++)
{
table_insert(&table, &newrow);
}
table_print(&table);
return 0;
}