我是这个网站上的新手并且自学习如何在C中编程。以下代码编译时没有警告或错误并执行,但第二次打印运行与第一次完全相同,即我的冒泡排序例程没有工作。使用单个字母字符的类似版本工作得很好。对于我出错的地方,任何指针(咳咳......)都会受到赞赏 - 谢谢!
代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char * names[10] = {"Dave","Al","Roger","Gary","Marc","Tim","Bob","Cal","Sid","Joe"};
int beginning;
int end;
int didSwap;
char * temp = "This will be used to store names temporarily";
int ctr;
puts("\nHere are some random names:");
for (ctr = 0; ctr < 10; ctr++)
{
printf("%s\n", names[ctr]);
}
for (beginning = 0; beginning < 9; beginning++)
{
didSwap = 0;
for (end = beginning; end < 10; end++)
{
if (names[end] < names[beginning])
{
temp = names[end];
names[end] = names[beginning];
names[beginning] = temp;
didSwap = 1;
}
}
if (didSwap == 0)
{
break;
}
}
puts("\nHere are the random names now in alphabetical order:");
for (ctr = 0; ctr < 10; ctr++)
{
printf("%s\n", names[ctr]);
}
return(0);
}
答案 0 :(得分:3)
您无法将字符串与<
进行比较;您通常应该使用strcmp
函数(除非您需要不区分大小写的排序,...)。在C中,这些字符串是内存地址,因此您按字符串的地址而不是其值进行排序。