Thinking in C++读书笔记--2.2一个小型的C库

本文介绍了一个小型C语言库的实现,该库提供了一系列基本功能,如初始化、清理、添加元素等。通过使用结构体和函数,展示了如何管理内存中的元素集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//2.2一个小型的C库的头文件
typedef struct STATSHtag {
 int size;
 int quantity;
 int next;
 unsigned char* storage;
}Stash;
//注意,这些函数声明用的是标准的C风格函数声明
void initialize( Stash* S , int Size );
void cleanup( Stash* S );
int add( Stash* S , void* element );
void* fecth( Stash* S , int index );
int count( Stash* S );
void inflate( Stash* S , int increase );

//2.2一个小型C库的具体实现
#include "stdafx.h"
#include "lib.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>//memcpy()
#include <stdio.h>

void initialize( Stash* S , int Size ) {
 S->size = Size;
 S->quantity = 0;
 S->storage = 0;
 S->next = 0;
}

void cleanup( Stash* S) {
 if ( S->storage ) {
  puts( "freeing storage" );
  free(S->storage);
 }
}

int add( Stash* S , void* element ) {
 if ( S->next >= S->quantity )
  inflate(S , 100);
 memcpy(&( S->storage[S->next * S->size]) , element , S->size);//第一个参数为目标地址,第二个参数为源地址,第三个参数是要拷贝的字节数
 S->next++;
 return ( S->next-1 );
}

void* fecth( Stash* S , int index ) {
 if ( index >= S->next || index < 0 )
  return 0;
 return &( S->storage[index * S->size] );
}

int count( Stash* S ) {
 return S->next;
}

void inflate( Stash* S , int increase ) {
 void* v = realloc( S->storage , ( S->quantity + increase ) * S->size );
 assert(v);
 S->storage = (unsigned char *)v;//书上原来是v的,但在C++中是无法通过编译的,所以强制转换了
 S->quantity += increase;
}
//在C中,可将void*赋给其他任何的指针,而且编译器能够通过.但在C++中,这个语句是不允许的.在C中,void*是(malloc,realloc,calloc的返回),而不需计算.C对类型不挑剔,所以它允许这种事情.但
//C++中对类型是严格的,允许将任何类型的指针赋给void*,但不允许将void*指针赋给其他任何类型的指针
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值