저는 C로 시작해서 막후에서 무슨 일이 벌어지고 있는지에 대해서는 거의 알려지지 않았습니다. 필자는 데이터 구조 클래스를 위해 그것을 배우면서 조금 더 어렵게 만듭니다.포인터로 C로 구조체 정렬하기
업데이트 : 프로그램을 제거한 후 메모리로 시작하여 다시 시작합니다. 나는 내가이 malloc에 오류가의 할당 및 할당 해제 기능 얻고있다 : Q1 (9882)의 malloc : *에 대한 오류 객체 0x7fff59daec08 : 포인터 * 디버깅 malloc_error_break에 중단 점을 설정 할당되지 않은 해제되지
갱신 2는 여기에 여전히 뭔가를 놓치고, 내 개정 된 코드입니다, 내 printf와 문장의 몇 게재되지 않습니다
#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;
}
숙제 태그 [사용되지]입니다 (http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated). – chris
답변을 무효화하므로 코드를 수정하지 마십시오. 새 질문을 제출하십시오. 나는 당신이 그걸 보았다는 것을 알았습니다 ... 당신의 새로운 질문에 대한 광범위한 답변을보십시오. 그리고 정답을 받아들이면, 아무도 시간을들이는 데 방해가 될 것입니다. –