我試圖在C中使用快速排序練習。我的程序是一個簡單的結構數組,它接受命令行參數(名稱1年齡1名稱2年齡2 ...等)並以降序輸出所述年齡。快速排序功能只適用於最後一個值是最大的
只有最後輸入的年齡最大才能正常工作。除此之外,我得到沒有輸出或Seg Fault 11.有沒有人有任何想法?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NameLen 80
void print_struct();
struct people
{
char name [NameLen + 1];
int age;
}; //defining a structure//
typedef struct people PERSON;
void quicksort(struct people list[],int,int);
int main(int argc, const char * argv[])
{
int i,j;
j = 0;
int l = ((argc/2)-1);
struct people list[l]; //maximum size of array of structs
if (argc %2 == 0) //if the number of arguments is an even number
{
printf("Invalid Arguments!\n");
printf("Usage : ./hw5 name1 age1 name2 age2 ... "); //print error message and correct program usage
exit(0);
}
printf("You have entered %d persons(s) into the program \n",(argc/2));
for (i=1; i < argc; i+=2)
{
strcpy(list[j].name, argv[i]);
list[j].age = atoi(argv[i+1]);
if(list[j].age == 0)
{
printf("...Invalid age <=0. Try again.\n");
exit(0);
}
j++;
}
printf("Unsorted Names: \n");
print_struct(&list,argc);
printf ("Sorted by Age: \n");
quicksort(list,0 ,j);
for(i=0;i<j;i++){
printf("Name : %s| Age : %d\n", list[i].name, list[i].age);}//possible error here?
//Quicksort Function
保持一致的代碼風格肯定會提高可讀性。 – Kupiakos
謝謝@Kupiakos!這是我第二次發佈,所以我會繼續努力! – QuesionableCode
以方便閱讀和理解1)一致縮進代碼2)使用一致的垂直間距3)遵循的公理:*每行只有一個聲明,(最多)每聲明一個變量聲明* – user3629249