# 函数实现既能开辟新空间、又能对原来空间大小进行调整、并且能对新增部分设置为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)
{
}
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 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)