我试图在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