65,211
社区成员
发帖
与我相关
我的任务
分享int current_element=0;
int total_element=5;
char *dynamic = NULL;
void bufmalloc()
{
dynamic=(char*)malloc(total_element);
if(dynamic == NULL)//判断一下
{
exit(1);
}
}
void add_element(char c)
{
if(current_element == total_element-1)
{
total_element*=2;
if((dynamic =(char*)realloc(dynamic, total_element))== NULL) //应该这样,原来那样内存泄漏
{
perror("Couldn't expand the table\n");
exit(1);
}
}
//current_element++;
dynamic[current_element++]=c; //将上一句放在赋值后面,否则0位置没有使用
}
int main()
{
char c;
int i;
bufmalloc();
for(i=0;i <3;i++)
{
scanf("%c",&c);//应该这样,scanf中别加和输入无关的字符
add_element(c);
fflush(stdin);
}
printf("current_element is %d\n",current_element);
printf("dynamic[] is %s\n", dynamic); //输出的是字符串
free(dynamic); //释放内存
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int current_element=-1;
int total_element=5;
char *dynamic;
void bufmalloc()
{
dynamic=(char*)malloc(total_element);
}
void add_element(char c)
{
if(current_element==total_element-1)
{
total_element*=2;
if((char*)realloc(dynamic, total_element)==NULL)
{
perror("Couldn't expand the table\n");
exit(0);//////出错就直接退出了
}
//else /////////////////这里没必要重新分配,前面if已经执行了
//{
// dynamic=(char*)realloc(dynamic, total_element);
//}
}
current_element++;
dynamic[current_element]=c;
}
int main(void)
{
char c;
int i;
bufmalloc();
for(i=0;i <3;i++)
{
printf( "Input char:" );
scanf("%c",&c);
add_element(c);
fflush(stdin);
printf( "\n" );
}
printf("current_element is %d\n",current_element+1); /////////////
printf("dynamic[] is %c\n",dynamic[0]); /////////////////用%c输出
return 0;
}
if((char*)realloc(dynamic, total_element)==NULL)
{
perror("Couldn't expand the table\n");
}
else
{
dynamic=(char*)realloc(dynamic, total_element); //既然if的部分他已经扩展了内存,你再realloc干吗?
}
if((char*)realloc(dynamic, total_element)==NULL)
{
perror("Couldn't expand the table\n");
}
else
{
dynamic=(char*)realloc(dynamic, total_element); //既然if的部分他已经失败了,你再调用有什么意义?
}