2017-06-09 146 views
0

我正在从C Programming for the Absolute Beginner 2nd Edition开始第8章挑战3。该程序应该按字母顺序对一组名称进行排序。对预定义的名称列表进行排序

我的程序不工作。主要功能没有sort()工作,但排序功能搞砸了;根据警告消息,strcmp()似乎也被错误地使用。

我使用的编译器是gcc,我用nano写了代码。

/* Uses strcmp() in a different function 
    to sort a list of names in alphabetical order */ 

#include <stdio.h> 
#include <string.h> 

void sort(char*, int); 

void main() { 
    char strStates[4][11] = { "Florida", "Oregon", "California", "Georgia" }; 
    sort(*strStates, 4); // 4 is the number of string in the array 

    printf("\nFour States Listed in Alphabetical Order\n"); 

    int x; 
    for(x = 0; x < 4; x++) 
     printf("\n%s", strStates[x]); 
} 

void sort(char* strNames, int iStrings) { 
    char strPlaceholder[11] = { 0 }; 
    int x; 
    int y; 

    for(x = 0; x < iStrings; x++) { 
     for(y = 0; y < iStrings - 1; y++) { 
      if(strcmp(strNames[y], strNames[y + 1]) > 0) { 
       strcpy(strPlaceholder, strNames[y + 1]); 
       strcpy(strNames[y + 1], strNames[y]); 
       strcpy(strNames[y], strPlaceholder); 
      } 
     } 
    } 
} 
+0

请把你的代码 – FieryCat

+5

请附上您的程序问题,直接的文字。将代码复制到编辑框中。确保它看起来不错,忽略预览然后选择代码并使用框上方的**按钮缩进它。现在检查预览。确保您复制的代码中没有选项卡;当你缩进时会破坏布局。 –

+0

'sort'的参数类型不正确。 – BLUEPIXY

回答

0

不是作为答案,而是作为让你前进的提示。像char[4][11]这样的二维数组与指向诸如char*之类的(序列)字符的指针是不同的。

假设以下代码:

char *s = "Florida"; // lets pointer 's' point to a sequence of characters, i.e. { 'F', 'l', 'o', 'r', 'i', 'd', 'a', '\0' } 
char arr[2][11] = { "Florida", "New York" }; 

然后,像s[1]的表达式相当于*(s + sizeof(char)),这是*(s+1),而像arr[1]的表达式相当于*(arr + sizeof(char[11])),这是*(arr + 11),不*(arr + 1)。 “sizeof”部分由编译器完成,并根据变量的类型派生。因此char*类型的参数表现与char[11]类型的参数不同。

下面的代码可以帮助你前进:

void print (char array[][11], int n) { 

    for(int i=0;i<n;i++) 
     printf("%d:%s\n",i,array[i]); 
} 

int main() { 

    char strStates[4][11] = { "aer", "adf", "awer", "aert" }; 
    print (strStates,4); 

    return 0; 
} 
+0

@BLUEPIXY:糟糕,尝试解释一系列字符采用了完全错误的方式:-) –

相关问题