【发布时间】:2017-11-12 16:55:51
【问题描述】:
我想用 realloc(memory allocator) 在 struct 上记录我的一些学生信息。当我尝试解决这个问题时;我将按给定的 id 对数据进行排序,但每个 id 都有一些关于 whoose id 学生的附加信息。我按 id 对结构进行排序,但是当我将每个数据移动到另一个数据编译器时,不要这样做。请问你能帮我吗?注意:我并不是要将结构移动到另一个结构。我只是想将 strcut 数组的一个元素值移动到另一个数组元素值或更改排序数据的这些数据位置
#include <string.h>
#include <stdlib.h>
typedef struct {
int id;
char name[10];
char surname[10];
double quiz1;
double quiz2;
double quiz3;
double midterm;
double finall;
}STUDENT;
int indis = 0;
void swapInt(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void swapDouble(double *a, double *b)
{
double temp = *a;
*a = *b;
*b = temp;
}
void str_swap(char const ** str1, char const ** str2)
{
char const *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
void sortSt(STUDENT *st) {
int i, j, min;
for (i = 0; i < indis - 1; i++) {
min = i;
for (j = i + 1; j < indis; j++)
if (st[j].id < st[min].id) {
min = j;
// Swap the found minimum element with the first element
memcpy()
swapInt(&st[min].id, &st[i].id);
str_swap(&st[min].name, &st[i].name);
swapChar(st[min].surname, st[i].surname);
swapDouble(&st[min].quiz1, &st[i].quiz1);
swapDouble(&st[min].quiz2, &st[i].quiz2);
swapDouble(&st[min].quiz3, &st[i].quiz3);
swapDouble(&st[min].midterm, &st[i].midterm);
swapDouble(&st[min].finall, &st[i].finall);
}
}
}
【问题讨论】:
-
是的,我知道这个功能,但我不是这个意思。或者我不能使用这个功能。我这样写 memcpy(st[j], st[min], 8);这行不通。你能帮帮我吗? @IgorPavkovic
-
其实主要的问题是,程序应该显示学生名单,名字和姓氏(按学生ID排序)。这该怎么做?我不想问所有问题,但我愿意理解解决问题的技巧。
-
为什么不直接交换学生,而不是一一交换每个字段?复制您的
swapInt函数,但将int更改为STUDENT。