动态分配内存,可根据输入设置数组大小
malloc头文件#include <string.h>
swap头文件#include <iostream> 记得用using namespace std;
#include <stdio.h> #include <iostream> #include <algorithm> using namespace std; void sort(int *score, int *id, int n); int main() { int n, *id, *score; printf("Input number:\n"); scanf("%d", &n); id = (int *)malloc(sizeof(int)*n); score = (int *)malloc(sizeof(int)*n); printf("Input number, score:\n"); for (int i = 0; i < n; i++) { printf("第%d个学生:", i + 1); scanf("%d %d", id + i, score + i); } sort(score, id, n); printf("排序后:\n"); for (int i = 0; i < n; i++) { printf("第%d个学生", i + 1); printf("id:%d\tscore:%d\n", *(id + i), *(score + i)); } return 0; } void sort(int *score, int *id, int n) { int i, j, k; for(i = 0; i < n-1; i++) { k = i; for(j = k+1; j < n; j++) { if(score[j] > score[k]) k = j; } if(k != i) { swap(score[i], score[k]); swap(id[i], id[k]); } } }