关闭

函数实现既能开辟新空间、又能对原来空间大小进行调整、并且能对新增部分设置为0

229人阅读 评论(0) 收藏 举报
分类:

getmem.h

#ifndef GETMEM_H_
#define GETMEM_H_

#include <stdlib.h>
#include <string>
using namespace std;

template<class T>
void getmem(T*& oldmem, int elems)
{
	typedef int cntr;
	const int csz = sizeof(cntr);
	const int Tsz = sizeof(T);
	if (elems == 0)
	{
		free(&(((cntr*)oldmem)[-1]));
		return;
	}
	T* pp = oldmem;
	cntr* p = (cntr*)pp;
	cntr oldcount = 0;
	if (pp)
	{
		p = (cntr*)pp;
		p--;
		oldcount = *(cntr*)p;
	}
	T* m = (T*)realloc(p, elems * Tsz + csz);
	*((cntr*)m) = elems;
	const cntr increment = elems - oldcount;
	if (increment > 0)
	{
		long startadr = (long)&(m[oldcount]);
		startadr += csz;
		memset((void*)startadr, 0, increment * Tsz);
	}
	oldmem = (T*)&(((cntr*)m)[1]);
}

template<class T>
inline void freemem(T* m)
{
	getmem(m, 0);
}

#endif

getmem.cpp

#include "getmem.h"
#include <iostream>
using namespace std;

int main()
{
	int* p = 0;
	getmem(p, 10);
	for (int i = 0; i < 10; i++)
	{
		cout << p[i] << ' ';
		p[i] = i;
	}
	cout << '\n';
	getmem(p, 20);
	for (int j = 0; j < 20; j++)
	{
		cout << p[j] << ' ';
		p[j] = j;
	}
	cout << '\n';
	getmem(p, 25);
	for (int k = 0; k < 25; k++)
	{
		cout << p[k] << ' ';
	}
	freemem(p);
	cout << '\n';

	float* f = 0;
	getmem(f, 3);
	for (int u = 0; u < 3; u++)
	{
		cout << f[u] << ' ';
		f[u] = 3.14159f;
	}
	cout << '\n';
	getmem(f, 6);
	for (int v = 0; v < 6; v++)
	{
		cout << f[v] << ' ';
	}
	freemem(f);

	system("pause");
	return 1;
}


0
0

  相关文章推荐
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8097次
    • 积分:278
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:2篇
    • 译文:17篇
    • 评论:0条
    文章分类