2013-01-05 33 views
0

我有2个问题。一个关于realloc和一个关于qsort排序的问题。在下面的代码中,我一直在为“temp = realloc(input,(i + 1)* sizeof(int));”而崩溃,但对于“i + 2”,一切正常。为什么? :/ 我把整数在数组中,直到输入一个整数“< 0”。然后我打印一些地址。用qsort在c中排序

#include <stdio.h> 
    #include <stdlib.h> 

    int main() 
    { 
     int *input,*temp,*f,*l; 
     input=malloc(sizeof(int)); 
     int x,i,counter; 
     counter=0; 
     i=0; 
     while (x>=0) 
     { 
      scanf("%d",&x); 
      if(x<0) break; 
      input[i]=x; 
      temp=realloc(input,(i+2)*sizeof(int)); 
      counter++; 
      i++; 
      if (temp!=NULL) input=temp; 
      else 
      { 
        free(input); 
        printf("Error allocating memory!\n"); 
        return 1; 
      } 
     } 
    for(i=0; i<counter; i++) printf("Input: %d",input[i]); 
    printf("table address: %p",&input); 
    printf("first element address: %p",&input[0]); 
    printf("last element address: %p",&input[counter-1]); 
    } 

关于使用qsort对此数组进行排序。我发现这个代码作为一个例子在“cplusplus.com”:

/* qsort example */ 
    #include <stdio.h> 
    #include <stdlib.h> 

    int values[] = { 40, 10, 100, 90, 20, 25 }; 

    int compare (const void * a, const void * b) 
    { 
     return (*(int*)a - *(int*)b); 
    } 

    int main() 
    { 
     int n; 
     qsort (values, 6, sizeof(int), compare); 
     for (n=0; n<6; n++) 
     printf ("%d ",values[n]); 
     return 0; 
    } 

我无法理解如何指针a和b连接到例如阵列。如果我想使用不同的排序算法,或者从大到小排序,我应该改变“return((int)a - (int)b);”?? 在此先感谢!

+5

这是两个独立的话题,所以应该问作为两个独立的堆栈溢出的问题... –

+0

不好意思啊,不知道:/ – alex777

回答

1
  1. 您不应该在这里使用realloc。你知道表的大小是多少,它是x。因此在第一张长度为x的表格中分配malloc。此外,for回路在这里更适合,而不是while。只是一个风格上的改进。

  2. 是的,你改变那部分,它应该是(*(int*)b - *(int*)a)排序从大到小。

+0

谢谢..我会检查的qsort的源代码了解指针。关于realloc,我尝试了不同的东西..似乎我最终必须学会使用调试器来找出关于内存的一些事情! – alex777

+0

该数组的长度不是x。该数组具有动态长度。它存储所有的整数“x”,直到用户按下一个小于0的整数!对不起,没有在那里发表评论... – alex777