2017-08-07 55 views
0

我是这个网站的新手,并且自学了如何用C编程。下面的代码编译时没有警告或者错误并且执行,但是第二次打印运行和首先,即我的气泡排序例程不起作用。这种使用单字母字符的类似版本工作得很好。任何指针(嗯...)将不胜感激我去哪里错了 - 谢谢!为什么我的冒泡排序在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); 
} 
+2

你做了什么调试? – Carcigenicate

+1

对于字符串,使用'strcmp'而不是'<'。 – BLUEPIXY

+0

没有,因为没有错误或警告显示出来,否则我会陷入困境。我尝试用许多不同的方式重写(这会产生警告),但没有运气... –

回答

3

不能有效地与<比较字符串;您通常应该使用strcmp函数(除非您需要区分大小写的排序,...)。在C中,这些字符串是内存地址,所以您按字符串的地址排序而不是它的值。

+0

是的,我越来越多地了解字符串 - 感谢您的意见。 –