动态Array和动态KeyValue(优化版my_table,segment段分配)

本文介绍了C语言中my_table数据结构的定义和实现,包括table_create、table_extend、table_insert和table_print函数,展示了如何动态管理内存并插入数据。
摘要由CSDN通过智能技术生成

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值