实现一个字符串缓冲区---【VIPKID面试题】

和面试官聊到内存管理的问题,然后让我实现一个字符串缓冲区的类,想到了思路,但是最后写出来的代码实在跟shi一样;凉凉了!!!
、、、、、、、、、、、、、、、、、
以下是实现一个字符串缓冲区的类;
实现的不好,请大家指正!
、、、、、、、、、、、、、、、、、

#define _CRT_SECURE_NO_DEPRECATE 1
#include<stdio.h>
#include<iostream>
#include<stdlib.h>

using namespace std;

class Buffer
{
public:
	Buffer(int size)
	{
		array = (char*)malloc(size);
		Size = 0;
		Capacity = size;
		for (int i = 0; i < Capacity; ++i)//缓冲区初始化为'\0'
			array[i] = '\0';
	}
	~Buffer()
	{
		free(array);
		array = NULL;
		Size = 0;
		Capacity = 0;
	}

	//从缓冲区读数据读到buf中
	char Read(char* buf, int read_size);
	//把buf中的数据写进缓冲区
	char Write(const char* buf, int write_size);

private:
	char* array;
	int Size;
	int  Capacity;
};

char Buffer::Read(char* buf, int read_size)
{
	int count = 0;
	if (read_size == 0||Size == 0)
		return count;
	int ret = Size;
	for (int i = 0; i < read_size; ++i)
	{
		if (i >= ret)
			break;
		buf[i] = array[i];
		--Size;
		++count;
	}
	return count;
}

char Buffer::Write(const char* buf, int write_size)
{
	int count = 0;
	if (write_size >= Capacity)
	{
		char* tmp = array;
		int new_Size = write_size;
		int new_Capacity = write_size;
		array = (char*)malloc(write_size);
		for (int i = 0; i < Size; ++i)
		{
			array[i] = tmp[i];
		}

		for (int i = Size; i < write_size; ++i)
		{
			array[i] = '\0';
		}
		free(tmp);
		tmp = NULL;
		Size = 0;
		Capacity = new_Capacity;
	}
	for (int i = 0; i < write_size; ++i)
	{
		array[i] = buf[i];
		++Size;
		++count;
	}
	return count;
}


int main()
{
	Buffer b(1024);
	char buf[] = "hello";
	char res[1024] = { '\0' };
	b.Write(buf, sizeof(buf) / sizeof(buf[0]));
	b.Read(res, 1024);
	b.Write(" world", 10);
	char res1[1024] = { '\0' };
	b.Read(res1, 1024);
	printf("%s\n", res1);

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值