我刚从 C 语言开始,对幕后发生的事情知之甚少。我正在为一个数据结构类动态学习它,这使事情变得有点困难。
更新:我已经剥离了程序,并从内存开始。我在那里有分配和解除分配函数,我得到一个 malloc 错误:Q1(9882)malloc:* 对象 0x7fff59daec08 的错误:未分配被释放的指针 *在 malloc_error_break 中设置断点以进行调试
Update2 这是我修改后的代码,它仍然缺少一些东西,我的一些 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;
}