//c语言申请内存 malloc 和realloch calloc
#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
void printff(int array[],int arrayNum)
{
for (int i = 0; i < arrayNum; i++)
{
cout << array[i] <<"\t"<< "";
}
cout << endl;
}
void testCalloc()
{
int *pMNum = (int *)malloc(sizeof(int*) * 3);
if (pMNum == nullptr)//申请后记得安全处理
return;
memset(pMNum, 0, sizeof(int) * 3); //memset(pMNum, 2, sizeof(int) * 3);//calloc等于malloc加memset函数初始化,且初始化的值都是0字节,也就没有数据,值自然是为0
printff(pMNum, 3);//malloc不做初始化,输出数组内的值为系统随机值,
delete(pMNum);
pMNum = nullptr;
int *pCNum = (int *)calloc(3, sizeof(int));
printff(pCNum, 3);//calloc初始化数组的值为0
delete(pCNum);
pCNum = nullptr;
//realloc是再次申请,当之前申请不够时,扩大使用。
int *pint = (int *)malloc(sizeof(int));
if (pint == nullptr)
return;
*pint = 1999;
cout << *pint << endl;
pint = (int*)realloc(pint, sizeof(int)*3);//再次申请三个int大小的内存,接在之前的内存后方
pint[1] = 13;
pint[2] = 45;
cout << pint[0] << "\t" << pint[1] << "\t" << pint[4] << "\t" << endl;//可以看出pint[4]没有做初始化为0字节的操作
delete(pint);
}
void testAuto()
{
auto p = new int[3]{1, 2, 3};//auto xxx这里变量会隐式转换为*XXX的指针变量
for (int i = 0; i < 3; i++)
{
cout << p[i] <<"\t"<< "";
}
cout << endl;
}
int main()
{
testCalloc();
testAuto();
}
|