Я пытаюсь отсортировать массив указателей, в зависимости от строк, на которые они указывают.Кажется, моя реализация пузырьковой сортировки игнорирует последний элемент, который я передаю.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char **a,char **b);
int main(void);
int main(void)
{
char *ptr[1000]; //build an array of 1000 pointers
short ptrpos = 0; //start at 0th pointer
char input[500];
printf("Enter strings(names), seperate by newline\nEOF(Ctrl-D) finishes the input process.\n");
while(fgets(input,sizeof(input),stdin))
{
ptr[ptrpos] = malloc(strlen(input)+1);
strcpy(ptr[ptrpos],input);
ptrpos++;
}
short length = ptrpos-1;
//BEGIN BUBBLE SORT
for(short h = 1; h < length; h++)
{
for(short i = 0;i < length - h; i++)
{
if(strcmp(ptr[i],ptr[i+1]) > 0)
swap(&ptr[i],&ptr[i+1]);
}
}
//END BUBBLE SORT
printf("\n----- Sorted List -----\n");
for(ptrpos = 0;ptrpos <= length;ptrpos++)
printf("%s",ptr[ptrpos]);
return 0;
}
void swap(char **a,char **b) //swaps adresses of passed pointers
{
char *temp = *a;
*a = *b;
*b = temp;
}
Вывод выглядит так:
Enter strings(names), seperate by newline
EOF(Ctrl-D) finishes the input process.
Echo
Charlie
Foxtrot
Alpha
Golf
Bravo
Delta
----- Sorted List -----
Alpha
Bravo
Charlie
Echo
Foxtrot
Golf
Delta
Почему игнорируется последняя строка?Я что-то упускаю из виду?