鱼C论坛

 找回密码
 立即注册
查看: 1871|回复: 3

[已解决]用realloc动态申请内存出现以下提示

[复制链接]
发表于 2017-7-16 12:56:37 | 显示全部楼层    本楼为最佳答案   
2017-07-16_125506.png
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //输入若干数字,从小到大排序

  4. void quick_sort(int array[], int left, int right); //从小到大排序

  5. int main(void)
  6. {
  7.         int i = 0;
  8.         int num = 0;
  9.         int count = 1;
  10.         int *ptr;

  11.                 ptr = (int *)malloc(sizeof(int));
  12.         printf("Please input numbers(double '-1' to end):\n");
  13.         do
  14.         {
  15.                 scanf("%d", &num);
  16.                 ptr = (int *)realloc(ptr, count * sizeof(int));
  17.                 if(ptr == NULL)
  18.                 {
  19.                         perror("realloc");
  20.                         exit(-1);
  21.                 }
  22.                 ptr[count-1] = num;
  23.                 count++;
  24.         }while(ptr[count-2] != -1 || num != -1);
  25.         quick_sort(ptr, 0, count - 3);
  26.         for(i = 0; i < count - 2; i++)
  27.         {
  28.                 printf("%d ", ptr[i]);
  29.         }
  30.         putchar('\n');
  31.         free(ptr);
  32.         return 0;
  33. }

  34. void quick_sort(int array[], int left, int right) //从小到大排序
  35. {
  36.         int temp, pivot;
  37.         int i = left, j = right;
  38.         pivot = array[(left + right) / 2];
  39.         while(i <= j)
  40.         {
  41.                 while(array[i] < pivot)
  42.                 {
  43.                         i++;
  44.                 }
  45.                 while(array[j] > pivot)
  46.                 {
  47.                         j--;
  48.                 }
  49.                 if(i <= j)
  50.                 {
  51.                         temp = array[j];
  52.                         array[j] = array[i];
  53.                         array[i] = temp;
  54.                         i++;
  55.                         j--;
  56.                 }
  57.         }
  58.         if(left < j)
  59.         {
  60.                 quick_sort(array, left, j);
  61.         }
  62.         if(i < right)
  63.         {
  64.                 quick_sort(array, i, right);
  65.         }
  66. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-16 16:51:18 | 显示全部楼层
知表不言 发表于 2017-7-16 16:10
&#128591;十分感谢,我已经懂了,realloc的参数除了NULL必须是由malloc、calloc或realloc函数返回的值才 ...

给个最佳吧老板
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-28 07:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表