动态内存分配的问题
输入任意句话,保存到动态分配的内存中,然后按字数从短到长输出。但无法输出?
我用的是linux,那个setbuf是用来清空输入缓冲区的。
程序代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> int main() { char** p_pointers=NULL; int count=0; int capacity=0; char conti; char* temp=NULL; do { if(count==capacity) { capacity+=5; p_pointers=realloc(p_pointers,(capacity)*sizeof(char*)); } *(p_pointers+count)=malloc(100*sizeof(char)); setbuf(stdin,NULL); scanf("%s",*(p_pointers+count)); printf("Do you want to continue?( y or N )"); setbuf(stdin,NULL); scanf("%c",&conti); }while(tolower(conti)=='y'); for(int i=0;i<=count-2;i++) for(int j=i+1;j<=count-1;j++) if(strlen(*(p_pointers+i))>strlen(*(p_pointers+j))) { temp=*(p_pointers+i); *(p_pointers+i)=*(p_pointers+j); *(p_pointers+j)=temp; } for(int i=0;i<=count-1;i++) printf("%s\n",*(p_pointers+i)); free(p_pointers); }