我必须使用Bubble Sort技术按字典顺序排序字符串,而不使用任何库函数。我写了下面的代码在排序字符串时工作正常。
但问题是,如果我给Ñ作为输入(比如N = 4),I只能输入n-1个字符串(仅3个字符串)。 该问题可以通过运行for循环从0到n来解决,但这不是一个合理的解决方案。
我在这里做错了什么?C:字符串数组 - 只能输入n-1个字符串,输入大小为n
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void swap(int indx[], int j)
{
int temp;
temp = indx[j];
indx[j] = indx[j+1];
indx[j+1] = temp;
}
void sort(char **str, int indx[], int n)
{
int i, j, k;
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
k = 0;
while(str[j][k] != '\0')
{
if((str[indx[j]][k]) > (str[indx[j+1]][k]))
{
swap(indx, j);
break;
}
else if((str[indx[j]][k]) < (str[indx[j+1]][k]))
break;
else
k++;
}
}
}
}
void display(char **str, int indx[], int n)
{
int i;
printf("Sorted strings : ");
for(i=0; i<n; i++)
printf("%s\n", str[indx[i]]);
}
int main(void)
{
char **str;
int n, i, j, *indx;
printf("Enter no. of strings : ");
scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
我不明白... 1)为什么你只输入n-1字符串?你没有说出什么问题。 2)为什么从0到n运行循环是“不合逻辑的”? – 2013-05-08 15:33:18
注意:C标准说''malloc()'在''(不是'')中声明;它也不会谈论任何名为''的头文件。 –
pmg
2013-05-08 15:34:36
@KScottPiel为了回答你的第一个问题,我们以这个例子为例,如果我给“输入字符串数”4,那么我实际上只能输入3个字符串。 要回答你的第二个问题,如果我们从0开始数组索引,我们通常会达到n-1。所以如果我们遍历从0到n的数组,我们实际上遍历了一个额外的元素,这根据我的知识是不合逻辑的。 – titan7585 2013-05-08 15:39:56