分类结构用C的指针 [英] sorting structs in C with pointers

查看:91
本文介绍了分类结构用C的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始在C和有很少的线索,这是怎么回事幕后。我正在学习它的飞行数据结构类,它使事情变得有点困难。

更新:我已经剥离计划回去,我开始有记忆和起来。我在那里的分配和释放功能,我得到一个malloc错误:Q1(9882)的malloc: *错误对象0x7fff59daec08:指针被释放没有被分配
*
在malloc_error_break设置一个断点调试

UPDATE2这里是我的修订code,它仍然失去了一些东西,一对夫妇的printf我的语句都没有显示出来:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&MATH.H GT;
#包括LT&;&ASSERT.H GT;静态INT大小= 10;结构学生{
    INT ID;
    INT分;
};学生结构分配*(){
     / *分配内存为十名学生* /
     学生结构* S =的malloc(大小*(sizeof的(结构学生)));
     断言(S!= 0);
     / *返回指针* /
     返回S;
}无效生成(结构*学生学生){
    / *生成随机ID和分数十学生,ID为1和10之间0至100之间,分数* /
    函数srand((unsigned int类型)时间(NULL));
    INT ID [大小]
    诠释Ÿ;    的for(int i = 0; I<大小;我++){
        Y =兰特()%的大小+ 1;
        而(重复数据删除(ID,I,Y)){
            Y =兰特()%的大小+ 1;
        }
        ID [i] = Y;
    }    对于(INT J = 0; J<大小; J ++){
        (学生+ J) - GT; ID = ID [J]。
        (学生+ j)为 - >分数=兰特()%101;
        的printf(ID数:%d \\ tScore数:%d \\ n,(学生+ J) - GT; ID,(学生+ J) - GT;分);
    }
}INT重复数据删除(INT ID [],INT尺寸1,int i)以{
    为(中间体X = 0; X&下;尺寸1; X ++){
        如果(编号[X] ==ⅰ)
            返回1;
    }
    返回0;
}无效输出(结构*学生学生){
     / *输出约十个学生在格式的信息:
              ID1 Score1
              ID2 score2
              ID3 score3
              ...
              ID10 score10 * /
    排序(安培;学生);
    为(中间体X = 0; X&下;大小; X ++){
        的printf(ID数:%d \\ tScore数:%d \\ n,(学生+ X) - GT; ID,(学生+ X) - GT;分); //打印语句不显示
    }
}无效的排序(结构*学生学生){
    学生结构* SD =分配();    学生结构*螺栓;    的for(int i = 0; I<大小;我++){
        螺柱=放;生[I]
        SD [stud-> ID = *螺栓;
    }
    为(中间体X = 0; X&下;大小; X ++){
        的printf(ID数:%d \\ tScore数:%d \\ n,(SD + X) - GT; ID,(SD + X) - GT;分); //打印语句不显示
    }
    学生=统计处;
    DEALLOCATE(SD);
}无效汇总(结构*学生学生){
     / *计算并打印十名学生的分数最低,最高和平均* /}无效DEALLOCATE(结构*学生螺栓){
     / *从猛男*释放内存/
    免费(螺栓);
}诠释主(){
    结构学生*螺柱= NULL;
    焦C [] =------------------------------ \\ N的;
    / *呼叫分配* /
    螺柱=分配();
    / *调用生成* /
    生成(安培;螺柱);
    / *调用输出* /
    的printf(%S,C);
    输出(安培;螺柱);
    / *呼叫摘要* /    / *调用DEALLOCATE * /
    DEALLOCATE(螺栓);    返回0;
}


解决方案

 学生=放;生[X];

这改变了这里的学生点,所以通过循环下一次,你会从那里抵减,而不是从一开始。也就是说,你得到 originalstudents [0] originalstudents [1] originalstudents [1 + 2] originalstudents [1 + 2 + 3] ,等你有同样的问题与 SD

相反,你要使用一个不同的变量,像

 学生结构* ST =放;生[X];
的printf(ID =%d个\\ tscore =%d个\\ N,ST-> ID,ST->分);
等等

此外,什么是SD呢?你似乎分配一定的空间和学生复制到SD没有明显的原因。分配的空间不会保存或返还......这是一个内存泄漏。哦,等等,我看..你重新排序SD,学生们在ID的顺序。所以,你当你做到了应该释放内存。但对于学生和SD,你需要一个不同的指针数组,而不是数组的元素。还有,你可以使用许多不同的命名规则,但它是很好的使用一致的。例如:

 无效输出(结构*学生学生){
    学生结构* idstudents =分配(); / *通过编号的顺序排列* /
    如果(!idstudents)
        / *手柄分配出错* /;    为(中间体X = 0; X小于10; X ++){
        学生结构*学生=放;生[X];
        的printf(ID =%d个\\ tscore =%d个\\ N,以学生为>编号,以学生为>分);
        学生结构* idstudent =安培; idstudents [学生为> ID];
        * idstudent = *的学生; / *复制所有领域的一次* /
        的printf(ID =%d个\\ tscore =%d个\\ N,idstudent-> ID,idstudent->分); / *在这里毫无意义,因为我们刚刚通过的学生打印相同的信息* /
    }    为(中间体X = 0; X小于10; X ++){
        学生结构* idstudent =安培; idstudents [X];
        的printf(ID =%d个\\ tscore =%d个\\ N,idstudent-> ID,idstudent->分);
    }
    DEALLOCATE(idstudents);
}

I am just starting in C and have very little clue as to what's going on behind the scenes. I'm learning it on the fly for a data structures class which makes things a bit harder.

Update: I've stripped the program back down and am starting with memory and on up. I have the allocate and deallocate functions in there and I'm getting a malloc error: Q1(9882) malloc: * error for object 0x7fff59daec08: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

Update2 here's my revised code, it's still missing something, a couple of my printf statements aren't showing up:

#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<assert.h>

static int size = 10;

struct student{
    int id;
    int score;
};

struct student* allocate(){
     /*Allocate memory for ten students*/
     struct student *s = malloc(size*(sizeof(struct student)));
     assert(s != 0);
     /*return the pointer*/
     return s;
}

void generate(struct student* students){
    /*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0 and 100*/
    srand((unsigned int)time(NULL));
    int id[size];
    int y;

    for (int i = 0; i < size; i++){
        y = rand() % size + 1;
        while(dupe(id, i, y)){
            y = rand() % size + 1;
        }
        id[i] = y;
    }

    for (int j = 0; j < size; j++){
        (students + j)->id = id[j];
        (students + j)->score = rand() % 101;
        printf("ID: %d\tScore: %d\n", (students + j)->id, (students + j)->score);
    }
}

int dupe(int id[], int size1, int i){
    for (int x = 0; x < size1; x++){
        if(id[x] == i)
            return 1;
    }
    return 0;
}

void output(struct student* students){
     /*Output information about the ten students in the format:
              ID1 Score1
              ID2 score2
              ID3 score3
              ...
              ID10 score10*/
    sort(&students);
    for(int x = 0; x < size; x++){
        printf("ID: %d\tScore: %d\n", (students + x)->id, (students + x)->score); //print stmt not showing
    }
}

void sort(struct student* students){
    struct student *sd = allocate();

    struct student *stud;

    for(int i = 0; i < size; i++){
        stud = &students[i];
        sd[stud->id] = *stud;
    }
    for(int x = 0; x < size; x++){
        printf("ID: %d\tScore: %d\n", (sd + x)->id, (sd + x)->score); //print stmt not showing
    }
    students = &sd;
    deallocate(sd);
}

void summary(struct student* students){
     /*Compute and print the minimum, maximum and average scores of the ten students*/

}

void deallocate(struct student* stud){
     /*Deallocate memory from stud*/
    free(stud);
}

int main(){
    struct student* stud = NULL;
    char c[] = "------------------------------\n";
    /*call allocate*/
    stud = allocate();
    /*call generate*/
    generate(&stud);
    /*call output*/
    printf("%s", c);
    output(&stud);
    /*call summary*/

    /*call deallocate*/
    deallocate(stud);

    return 0;
}

解决方案

students = &students[x];

This changes where students points, so the next time through the loop you will be offseting from there, not from the beginning. That is, you're getting originalstudents[0], originalstudents[1], originalstudents[1+2], originalstudents[1+2+3], etc. You have the same problem with sd.

Instead you want to use a different variable, something like

struct student* st = &students[x];
printf("id = %d\tscore = %d\n", st->id, st->score);
etc

Also, what is sd for? You seem to allocate some space and copy students to sd for no apparent reason. The allocated space isn't saved or returned ... it's a memory leak. Oh, wait, I see .. you reorder the students in sd in order of their id. So you just should free the memory when you're done. But for both students and sd, you need a different pointer to the array than to the elements of the array. There are many different naming conventions you could use, but it's good to use a consistent one. For example:

void output(struct Student* students){
    struct Student *idstudents = allocate(); /* sorted by id */
    if (!idstudents)
        /* handle allocation error */;

    for (int x = 0; x < 10; x++){
        struct Student* student = &students[x];
        printf("id = %d\tscore = %d\n", student->id, student->score);
        struct Student* idstudent = &idstudents[student->id];
        *idstudent = *student; /* copy all fields at once */
        printf("id = %d\tscore = %d\n", idstudent->id, idstudent->score);/* pointless here, since we just printed the same info via student */
    }

    for (int x = 0; x < 10; x++){
        struct Student* idstudent = &idstudents[x];
        printf("id = %d\tscore = %d\n", idstudent->id, idstudent->score);
    }
    deallocate(idstudents);
}

这篇关于分类结构用C的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆