//_63_动态分配函数
//_63_main.cpp
//void *malloc(size_t size)//向系统申请内存空间
//void free(void *ptr)//释放内存空间
#include <stdio.h>
#include <stdlib.h>
#define NUMBER 5
int main()
{
//定义一个字符型的指针数组
char *str[NUMBER];
int t;
//为数组中的每个指针分配内存
for(t=0;t<NUMBER;t++)
{
//为每个指针分配内存地址,大小都为128个字节
if((str[t]=(char *)malloc(128))==NULL)
{
printf("Allocation Error.\n");
exit(1);
}
//在分配的内存中存放字符串
printf("Enter string %d: ",t);
gets(str[t]);
}
for(t=0;t<NUMBER;t++)
puts(str[t]);
//释放内存
for(t=0;t<NUMBER;t++)
free(str[t]);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define NUM 5
int main()
{
char *charArray[NUM];//指向char类型的指针数组
for(int k=0;k<NUM;k++)
{
charArray[k] = (char *)malloc(128);//为每个指针分配内存
if(charArray[k]==NULL)
exit(1);
printf("Please input the No.%d string: ",k+1);
gets(charArray[k]);
}
for(int k=0;k<NUM;k++)
{
puts(charArray[k]);
free(charArray[k]);
}
system("pause");
return 0;
}