【发布时间】:2018-11-17 02:20:16
【问题描述】:
我正在尝试对指针数组进行排序,具体取决于它们指向的字符串。我的冒泡排序实现似乎忽略了我传递给它的最后一个元素。
#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;
}
输出如下:
输入字符串(名称),用换行符分隔 EOF(Ctrl-D) 完成输入过程。 回声 查理 狐步舞 Α 高尔夫球 布拉沃 三角洲 ----- 排序列表 ----- Α 布拉沃 查理 回声 狐步舞 高尔夫球 三角洲
为什么最后一个字符串被忽略?我错过了什么明显的东西吗?
【问题讨论】:
标签: c sorting bubble-sort