C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Advanced Pointers

By David Bolton, About.com

8 of 8

Example 3 - Using qsort to sort Ints

Download Example 3 Listing of Example 3.
/* ex3 Sorting ints with qsort */
//

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

int comp(const int * a,const int * b)
{
  if (*a==*b)
    return 0;
  else
    if (*a < *b)
        return -1;
     else
      return 1;
}

int main(int argc, char* argv[])
{
   int numbers[10]={1892,45,200,-98,4087,5,-12345,1087,88,-100000};
   int i;

  /* Sort the array */
  qsort(numbers,10,sizeof(int),comp) ;
  for (i=0;i<9;i++)
    printf("Number = %d\n",numbers[ i ]) ;
  return 0;
}
Output of Example 3
Number = -100000
Number = -12345
Number = -98
Number = 5
Number = 45
Number = 88
Number = 200
Number = 1087
Number = 1892
The parameters to qsort are the address of the objects to be sorted, the number of objects, the size of each object and the function that compares two objects.

That completes this lesson on advanced use of pointers. In the next lesson, I'll look at some other advanced data structures.

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Example 3 - Using qsort to sort Ints

©2009 About.com, a part of The New York Times Company.

All rights reserved.