、
本题要求编写程序,读入5个字符串,按由小到大的顺序输出。
输入格式:
输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。
输出格式:
按照以下格式输出排序后的结果:
After sorted:
每行一个字符串
输入样例:
red yellow blue black white
输出样例:
After sorted:
black
blue
red
white
yellow
有没有大佬说一下这个程序为什么有段错误,还没学报错这一块
我看题目的时候忘看限制5个单词了,可恶,卡了我两天。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int compare(const void *a,const void *b)
{
const char *A = *(const char **)a;
const char *B = *(const char **)b;
return strcmp(A,B);
}
int main()
{
char **words = NULL;
char input[MAX];
int wordcount = 0;
fgets(input,sizeof(input),stdin);
input[strcspn(input,"\n")] = '\0';
char *token = strtok(input," ");
while(token != NULL)
{
words = (char **)realloc(words,(wordcount +1) * sizeof(char *));
words[wordcount] = strdup(token);
wordcount++;
token = strtok(NULL," ");
}
qsort(words,wordcount,sizeof(char *),compare);
printf("After sorted:\n");
for(int i =0;i<wordcount;i++)
{
printf("%s\n",words[i]);
free(words[i]);
}
free(words);
return 0;
}