【问题标题】:Sorting an array of structs in C with pointers用指针对C中的结构数组进行排序
【发布时间】:2018-04-17 22:12:50
【问题描述】:

我的 CIS 课程有一个编码作业。任务是编写一个程序,该程序将创建一个结构数组,该数组将保存最多 10 只狗的信息。在程序结束时,您应该按名称或大小对狗的数组进行排序。但是我无法对狗数组的排序进行编码。

我想知道如何对狗数组进行排序以供以后在主函数中使用。

代码

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

struct Dog{
    char name[20];
    int weight;
    int age;
    int ageDogYears;
    char size[7];
};

typedef struct Dog DG;

void calc(DG[], int);
void sort(DG[], int);
void display();

int main(){
    DG dArray[10];
    int x = 0;
    char str[80], *i;

    FILE *inFile;

    inFile = fopen("dogfile.txt", "r");
    if (inFile == NULL){
        printf("Error opening file");
        exit(1);
    }

    while(fgets(str, 80,inFile) != NULL){
        i = strtok(str, ", ");
        strcpy(dArray[x].name, i);
        puts(dArray[x].name);

        i = strtok(NULL, ", ");
        dArray[x].weight = atoi(i);
        printf("%d\n", dArray[x].weight);

        i = strtok(NULL, ", ");
        dArray[x].age = atoi(i);
        printf("%d\n", dArray[x].age);

        x++;
    }

    calc(dArray, x);

    sort(dArray, x);

    return 0;
}

void calc(DG dog[], int numDogs){
    int y, i, total;
    for(i = 0; i < numDogs; ++i){
        if(dog[i].weight <= 20){
            //sets the dog size to small
            strcpy(dog[i].size, "Small");

            for(y = 0; y < dog[i].age; ++y){
                if(y == 0)
                    total += 15;
                else if(y == 1)
                    total += 8;
                else if(y == 2)
                    total += 5;
                else
                    total += 4;
            }
        }
        else if(dog[i].weight <= 50){
            //sets the dog size to medium
            strcpy(dog[i].size, "Medium");

            for(y = 0; y < dog[i].age; ++y){
                if(y == 0)
                    total += 14;
                else if(y == 1)
                    total += 9;
                else if(y == 2)
                    total += 7;
                else
                    total += 5;
            }
        }
        else{
            //sets the dog size to Large
            strcpy(dog[i].size, "Large");

            for(y = 0; y < dog[i].age; ++y){
                if(y == 0)
                    total += 12;
                else if(y == 1)
                    total += 9;
                else if(y == 2)
                    total += 8;
                else
                    total += 7;
            }
        }

        dog[i].ageDogYears = total;
        total = 0;
    }
}

void sort(DG dog[], int numDogs){
    int sortType, i, y, temp;

    printf("\n wlould you like to sort by name(N) or size(S): ");
    scanf("%c", &sortType);

    switch(sortType){
        case 'N': case 'n':
            for(i = 0; i < numDogs; ++i){
                for(y = 0; y < (numDogs); ++y){
                    if(dog[y].weight > dog[y+1].weight){
                        temp = dog[y];
                        dog[y] = dog[y + 1];
                        dog[y + 1] = temp;
                    }
                }
            }
            break;
        default:
            if((sortType != 's') && (sortType != 'S'))
                printf("\n invalid input! Setting sort type to size.");
        //sorting of dog names
    }
}

示例输入

Fluffy,23,6 Fido,65,7 Pepper,44,5 Bowser,75,10 Victor,10,2 Sassy,51,1

任何帮助将不胜感激!谢谢。

【问题讨论】:

  • if(dog[y].weight &gt; dog[y].weight){ 我想你这里有一个错字。您正在将同一只狗与自己进行比较(两个指数都是y)。你想写什么样的类型?另外,请注意您的数组范围。
  • 感谢您的反馈,是的,我确实在该行中发现了一个错字。该行应为if(dog[y].weight &gt; dog[y+1].weight){。但根据我对冒泡排序的研究,它仍然应该是y。
  • 请向我们提供一个示例输入并将整个代码编写在一个块中。此外,我们无法访问calc 函数,只能访问原型。
  • temp 是一个int,而dog[y] 是一个结构,所以temp = dog[y] 应该会给你一个错误。
  • 再次检查您的索引。

标签: c arrays sorting struct bubble-sort


【解决方案1】:

在我看来,您的错误在于(尽管我将在下面执行其他 cmets)指定 %c 作为格式描述符以传递指向 int 的指针以进行匹配。您必须将指针传递给char 以使scanf(3) 选择放置角色的正确位置。您可能没有得到正确的字符或根本没有字符(这会导致程序中出现未定义的行为)

其他一些问题是您在请求按名称排序时使用结构的weight 字段(在n 输入字符上)和类似这样的其他错误。这包括您在内部循环限制条件中使用y &lt; (numDogs)(它必须是y &lt; (numDogs - 1),否则您会将y-esim 与y+1-esim 元素进行比较(超出数组范围)

另外,由于您对两个排序选项使用相同的算法,我应该在内循环(进行比较的地方)中包含switch 语句,否则会迫使您将相同的排序代码复制两次(用于整体排序算法),如:

for(i = 0; i < numDogs; ++i){
    for(y = 0; y < (numDogs - 1); ++y){
        int sortResultGreater;
        switch (sortType) {
        case 'n': case 'N':
             sortResultGreater = strcmp(dog[y].name, dog[y+1].name) > 0; 
             break;
        default: {  /* this should be done as soon as you know the sorting type, not here inside the loop, of course */
             static int not_already_printed = 1;
             if (not_already_printed) {
                 printf("Error, sortType must be [nNsS], defaulting to n\n");
                 not_already_printed = 0; /* so we don't get here again */
             }
        } /* scope of not_already_printed finishes here */
        /* no break used here to fallback to the next case */
        case 's': case 'S':
             sortResultGreater = dog[y].weight > dog[y+1].weight; 
             break;
        } /* switch */
        if(sortResultGreater){
            temp = dog[y];
            dog[y] = dog[y + 1];
            dog[y + 1] = temp;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 2012-09-26
    • 2020-03-15
    • 2016-11-29
    • 2015-12-13
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多