这是对这个问题的跟进:
我已经修改了修改后的代码,我认为排序应该可以工作,但我感觉我没有正确使用指针。我的 printf 语句没有显示在控制台上,它们在评论中被标记。
我是 C 新手,所以这可能很明显,但我只是不知道如何在打印语句不打印时进行调试。
当前编译器警告:
Q1.c: In function 'generate':
Q1.c:28: warning: implicit declaration of function 'time'
Q1.c:35: warning: implicit declaration of function 'dupe'
Q1.c: In function 'output':
Q1.c:61: warning: implicit declaration of function 'sort'
Q1.c: At top level:
Q1.c:68: warning: conflicting types for 'sort'
Q1.c:61: warning: previous implicit declaration of 'sort' was here
Q1.c: In function 'sort':
Q1.c:82: warning: implicit declaration of function 'deallocate'
Q1.c: At top level:
Q1.c:90: warning: conflicting types for 'deallocate'
Q1.c:82: warning: previous implicit declaration of 'deallocate' was here
代码是:
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
int SIZE = 10;
static char c[] = "------------------------------\n";
struct student{
int id;
int score;
};
struct student* allocate(){
/*Allocate memory for ten students*/
struct student *s = malloc(SIZE* sizeof*s);
/*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++){
do{
y = rand() % SIZE + 1;
} while(dupe(id, i, y));
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);
printf("post sort students.\n %s", c);
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 -1] = *stud;
}
printf("sorted SD.\n %s", c);
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;
/*call allocate*/
stud = allocate();
/*call generate*/
generate(stud);
/*call output*/
printf("%s", c);
output(stud);
/*call summary*/
/*call deallocate*/
deallocate(stud);
return 0;
}