私はCでクイックソートを使用しようとしています。私のプログラムは、コマンドライン引数(name1 age1 name2 age2 ...など)前記年齢を降順に出力する。クイックソート機能は、最後の値が最大の場合にのみ有効です
最後に入力した年齢が一番大きい場合のみ正しく動作します。それ以外は出力も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!これは私の2回目の投稿ですので、私はそれに取り組んでいきます! – QuesionableCode
1)コードを一貫してインデントする2)一貫した垂直スペーシングを使用する3)公理に従う:* 1行につき1つのステートメントとステートメントごとに1つの変数宣言を書く* – user3629249