新手,因为完全做不来习题,干脆抄答案找茬。
程序代码://
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /*strlen()*/
int main(void)
{
char **pStr = NULL;
char *pBuffer = NULL;
int count = 0;
pStr = malloc(sizeof(char *));
do
{
pBuffer = malloc(100 * sizeof(char));
gets(pBuffer);
count++;
pStr = realloc(pStr,count * sizeof(char*));
*(pStr + count - 1) = pBuffer;
}while(strlen(pBuffer) !=0 );
for(int i=0; i<count-2; i++) /*-2很难理解啊*/
{
for(int j=0; j<count-2-i; j++)/*不减无所谓吧*/
{
if(strlen(*(pStr+j)) > strlen(*(pStr+j+1)))
{
pBuffer = *(pStr+j);
*(pStr+j) = *(pStr+j+1);
*(pStr+j+1) = pBuffer;
}
}
}
for(int i=0; i<count-1; i++)
{
printf("%s\n",*(pStr+i));
}
free(pStr);
return 0;
}
习题7.2 编写一个程序,从键盘读入任意个谚语,并将它们存储到执行期间分配的内存中。然后,将它们以字长顺序由短到长地输出。疑问:1,在for循环中,用于计数出现了两次 -2 ,其实不减也没问题吧?
2,free(Str) 是自行添加的,原文没有写,释放内存这样就可以了么?
3,原作者的书写方式,在写符号时,如 “1 + 1”,这样留出空格,是个人习惯,还是有合理的意义?
预谢
[此贴子已经被作者于2019-4-19 22:25编辑过]



