【发布时间】:2016-07-07 23:43:46
【问题描述】:
我正在尝试在 C 中练习使用快速排序。我的程序是一个简单的结构数组,它接受命令行参数(name1 age 1 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!这是我第二次发帖,所以我会继续努力!
-
为了便于阅读和理解 1) 一致地缩进代码 2) 使用一致的垂直间距 3) 遵循公理:每行只有一个语句和(最多)每个语句一个变量声明.
-
发布的代码无法编译。它缺少函数的结尾
main()。 -
计算
list[]数组大小的这一行:int l = ((argc/2)-1);不正确。这是一个整数除法。如果argc为7,则l的结果值应为3,但计算结果为2。建议从表达式中删除-1否则代码访问超出list[]数组的末尾,这会导致未定义的行为,并可能导致段错误事件。