Thread: qsort with array initialized using malloc?

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    2

    qsort with array initialized using malloc?

    Hello,

    This is my first post ever for trying to get help with code, so please go easy on me. I want to be honest, this is FOR homework, but is NOT homework. I have created this example to work from in order to understand qsort further because the next assignment requires it's use.

    Our teacher gave us this small piece of example code and I am trying to expand on it to serve my purpose.

    [C] Sorting - Pastebin.com

    The code gives me no errors, but does not sort the array. I'm very confused, and if somebody could clarify the use of qsort in this instance that would be amazing.

    I am imagining that the reason it's not sorting properly ( or at all ) is because of my comparison function. That is really just an assumption. Or perhaps I just don't understand the pointer array i'm using. Either way, I would really appreciate some advice.

    Thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Code:
    #include <stdio.h> /* printf */
    #include <stdlib.h> /* for malloc */
    #include <string.h> /* strcpy */
      
    #define WORDSIZE 20
      
    int compare2strs( const void *a, const void *b );
    void n( char array[][ WORDSIZE ], int N );
    void p( char array[][ WORDSIZE ], int N);
      
    int main()
    {
      
        int N = 10;
        char (*ptr)[WORDSIZE];
      
        ptr = malloc( N * sizeof(*ptr) );
      
        n( ptr, N );
        p( ptr, N);
        return( 0 );
    }
    int compare2strs( const void *a, const void *b )
    {
        char *left = (char *) a;
        char *right = (char *) b;
        return( strcmp( left, right ) );
    }
    void n( char array[][ WORDSIZE ], int N )
    {
        int i;
        for( i = 0; i < N; i++ )
        {
            strcpy( array[ i ], "Cluster!" );
        }
        strcpy( array[3], "try");
        strcpy( array[6], "to");
        strcpy( array[9], "sort");
        strcpy( array[1], "me");
      
        qsort( array, N,
                sizeof( array[ 0 ] ), compare2strs );
      
    }
    void p( char array[][ WORDSIZE ], int N){
        int i;
      
        for( i = 0; i < N; i++ ){
            printf("%s\n",array[i]);
        }
    }
    
    $ gcc foo.c
    $ ./a.out 
    Cluster!
    Cluster!
    Cluster!
    Cluster!
    Cluster!
    Cluster!
    me
    sort
    to
    try
    $
    > Our teacher gave us this small piece of example code and I am trying to expand on it to serve my purpose.
    The brutal way of assigning the initial pointer, then casting it to pass it to your functions is concerning.

    The main issue for it not working was this
    > sizeof( array ) / sizeof( array[ 0 ] )
    This only works on true arrays which are in scope at the time you use it.
    Function parameters (no matter how you declare them) are just pointers.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Your problem has nothing to do with the comparison function.

    The problem is that, when arrays are passed to functions, they are passed as pointers. The information about the actual size of the array (as seen by the caller) is lost.

    So the trick sizeof(array)/sizeof(array[0]) does not give the number of elements in the array within the function. sizeof(array) will always be the size of a pointer (which is 4 on a typical 32 bit system). You need to pass the array dimensions to your function as separate arguments.

    You'll see what I mean with this code.
    Code:
    #include <stdio.h>
    
    void func(int array[])
    {
         int n = (int)(sizeof(array)/sizeof(array[0]));
         printf("Number of elements computed in called function is %d\n", n);
    }
    
    int main()
    {
         int array[27];
         int n = (int)(sizeof(array)/sizeof(array[0]));
         printf("Number of elements computed in main() is %d\n", n);
         func(array);
    }
    Despite the calculation of size looking identical, it gives different results depending on where it occurs.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Mar 2013
    Posts
    2
    Thank you both so much!

    Such a simple fix too.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Static array of initialized members?
    By Blackroot in forum C++ Programming
    Replies: 4
    Last Post: 04-13-2009, 09:36 PM
  2. Still stuck using qsort + malloc!!
    By VegasSte in forum C Programming
    Replies: 16
    Last Post: 10-16-2002, 03:34 PM
  3. Using malloc() & qsort with a union revisited
    By Cyber Kitten in forum C Programming
    Replies: 11
    Last Post: 11-24-2001, 06:07 PM
  4. Using malloc() & qsort with a union
    By Cyber Kitten in forum C Programming
    Replies: 2
    Last Post: 09-02-2001, 07:57 AM