Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created July 27, 2016 09:40
Show Gist options
  • Save limboinf/3a17347b197a8661ac3045be9c7b5c73 to your computer and use it in GitHub Desktop.
Save limboinf/3a17347b197a8661ac3045be9c7b5c73 to your computer and use it in GitHub Desktop.
《C和指针》TOP11 为一个指定的数组分配内存并排序处理。
#include <stdio.h>
#include <stdlib.h>
int comp(const void *, const void *);
int main()
{
int *array;
int n_values;
int i;
printf("How many values are there?");
if(scanf("%d", &n_values) != 1 || n_values <= 0) {
printf("Illegal number of values.\n");
exit(EXIT_FAILURE);
}
//分配内存用于存储
array = malloc( n_values * sizeof( int ) );
if (array == NULL) {
printf("Can't get memory for that many values.\n");
exit(EXIT_FAILURE);
}
//初始化数组元素
for(i = 0; i < n_values; i++) {
printf("? ");
if(scanf("%d", array + i) != 1) {
printf("Error reading value #%d\n", i);
free(array); // 记得退出前要释放
exit(EXIT_FAILURE);
}
}
//排序
qsort(array, n_values, sizeof(int), comp);
//print
for(i = 0; i < n_values; i++) {
printf("%d\n", array[i]);
}
//释放内存并退出
free(array);
return EXIT_SUCCESS;
}
int comp(const void *a, const void *b)
{
register int const *pa = a;
register int const *pb = b;
return *pa > *pb ? 1 : *pa < *pb ? -1 : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment