###### 函数实现既能开辟新空间、又能对原来空间大小进行调整、并且能对新增部分设置为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]);
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;
}

#### 【基础知识】C/C++动态开辟空间

2014-06-19 00:14:56

#### C++中用new开辟内存空间和非new开辟内存空间的区别

2015-04-22 15:43:47

#### 链表反转不开辟新空间

2015-02-27 17:57:30

#### 如何扩大二维数组的大小（任何类型的通用版）

2012-10-21 15:10:28

#### C语言动态开辟存储空间创建链表

2014-09-30 19:36:19

#### 调整磁盘已有空间时的方法

2016-05-29 20:42:42

#### 简单介绍C语言三种动态开辟空间函数.

2015-02-13 13:41:57

#### Vector开辟多维大量空间

2017-03-30 20:17:38

#### 不开辟新空间反转单链表(递归版本)

2017-07-09 17:52:52

#### new delete 开辟空间和释放空间

2014-04-07 20:56:56