三种alloc的用法
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{
#if 0
//malloc 参数为申请的字节数
short *p = malloc(100); //size_t size 以字节为单位
if (NULL == p)
{
printf("malloc error\n");
return -1;
}
free(p);
//calloc 第一个参数为所需内存单元数量 第二个参数为内存单元的大小
int *q = calloc(100, sizeof(int)); //int a[100] int *p = a;
for (int i = 0; i<100; i++)
{
printf("%d\n", q[i]);
}
free(q);
//realloc 第一个参数为待扩容的指针(已经申请好的地址)
//第二个参数表示扩容后的内存大小
int *ptr = realloc(NULL, 400); //第一个参数若为NULL则此时的realloc相当于malloc
for (int i = 0; i<100; i++)
{
printf("ptr[%d] = %d\n", i, ptr[i]);
}
free(ptr);
#endif
//realloc的具体应用
char *ptr = (char*)malloc(100);
if (NULL == ptr)
return -1;
char *newPtr = (char*)realloc(ptr, 400);
if (NULL == newPtr)
{
printf("realloc error\n");
return -1;
}
strcpy(newPtr, "china");
//char arr[] = "ladjflasdjfk";
//scanf("%s",arr);
//strcpy(arr,"china");
printf("%s\n", newPtr);
free(newPtr);
//开始的ptr就不用free了 free(ptr)
return 0;
//realloc 只能扩容,不能缩小空间
//realloc newPtr ptr 有可能相等,也有可能不等。只使用realloc的返回指针
}