int main(void){ char *p[]={}; char *temp=NULL; int end=0; char y_n=0; int w=0;//这里 设为0 时 获取 0这个指示元素时出错,设为1时 没有问题 int gc=1;
while(true){ printf("enter content:\n"); while((end=getchar())!='\n'){ if(gc==1){ p[w]=(char *)calloc(gc,sizeof(char)); strcat(p[w],(char *)&end); } else{ temp=(char *)realloc(p[w],gc*sizeof(char)); if(temp==NULL){ printf("memory fail\n"); break; } p[w]=temp; /*here temp and p[w] reference same address so temp pointer set value is NULL break reference address so temp pointer not use free function. if temp pointer use free function,at the same time clean p[w] in memory address. */ temp=NULL; strcat(p[w],(char *)&end); } gc++; } printf("p[%d]:%s\n", w,p[w]); gc=1; w++;
printf("continue y or n:"); scanf("%c",&y_n); if(y_n=='n'){ break; }
temp=(char *)realloc(p[w],( gc +1)*sizeof(char)); if(temp==NULL){ printf("memory fail\n"); break; } p[w]=temp; /*here temp and p[w] reference same address so temp pointer set value is NULL break reference address so temp pointer not use free function. if temp pointer use free function,at he same time clean p[w] in memory address. */ temp=NULL; //strcat(p[w],(char *)&end); p[w][gc] = '\0'; p[w][gc-1] = end; } gc++; }