#define _STDC_WANT_LIB_EXT1_ 1
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int capacity = 500;
char** pString = calloc(capacity,sizeof(char*));
char** pTemp = NULL;
size_t maxlen = 50;
char buf[maxlen];
int count = 0;
printf("Enter a string,enter empty line to end and print result.\n"); //提示信息
while(true)
{
fgets(buf,maxlen - 1,stdin);
if(strnlen(buf,maxlen) - 1 == 0)
//空行跳出循环
break;
if(buf[strnlen(buf,maxlen) - 1] == '\n') //解决末位的换行符
buf[strnlen(buf,maxlen) - 1] = '\0';
*(pString + count) = calloc(maxlen,sizeof(char));
//为字符串指针分配内存
if(!(strcat(*(pString + count++),buf)))
//将buf链接到分配好的字符串指针
return 1;
if(count == capacity)
//给char**增加容量
{
capacity += 5;
pTemp = pString;
pString = realloc(pString,capacity*sizeof(char*));
pString = pTemp;
pTemp = NULL;
}
}
int i = 0;
//冒泡排序
int j = 0;
for(i = 1;i < count;++i)
{
for(j = 0;j < count - i;++j)
{
if(strnlen(*(pString + j),maxlen) >
strnlen(*(pString + j + 1),maxlen))
{
strcpy(buf,*(pString + j));
strcpy(*(pString + j),*(pString + j + 1));
strcpy(*(pString + j + 1),buf);
}
}
}
printf("This is you just enter Strings:\n");
//显示结果
for(i = 0;i < count;++i)
printf("%s\n",*(pString + i));
for(i = 0;i < count - 1;++i)
//释放内存
free(*(pString + i));
free(pString);
return 0;
}
同是新手,那天刚做的,你可以参考一下我的思路,自己做一遍