Thread: qsort dynamic array of structs

  1. #1
    Registered User
    Join Date
    Sep 2020
    Posts
    1

    qsort dynamic array of structs

    Hi I just need help with this code when ever I try to run this code it says Segmentation fault (core dumped) . I think it could be my compare function . I want to sort to every struct in the array.



    Code Removed (Ignore)
    Last edited by akpr2000; 09-13-2020 at 08:03 AM. Reason: Code Removed

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,627
    Hard to say where you messed up, when you've deleted your code.

    But here's a sequence of exercises.
    Code:
    int array[5] = { 4, 1, 8, 3, 9 };
    qsort( array, 5, sizeof(array[0]), compare_fn);
    Then adjust for a structure.
    Code:
    struct foo {
      int a;
    };
    struct foo array[5] = { {4}, {1}, {8}, {3}, {9} };
    qsort( array, 5, sizeof(array[0]), compare_fn);
    Then adjust for a dynamic array.
    Code:
    struct foo {
      int a;
    };
    struct foo *array = malloc( 5 * sizeof(*array) );
    // initialise....
    qsort( array, 5, sizeof(array[0]), compare_fn);
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to Qsort an array of structs by one of its members?
    By Vespasian in forum C++ Programming
    Replies: 3
    Last Post: 03-31-2013, 01:36 PM
  2. Dynamic array of structs.. sentinal value?
    By dayalsoap in forum C Programming
    Replies: 4
    Last Post: 07-27-2012, 01:42 PM
  3. Dynamic Array of Structs help
    By fairguynova in forum C++ Programming
    Replies: 5
    Last Post: 02-04-2009, 11:20 PM
  4. Dynamic Array of Structs Help
    By Spawn in forum C++ Programming
    Replies: 3
    Last Post: 04-29-2006, 05:45 PM
  5. Qsort and Dynamic Array
    By Thantos in forum C Programming
    Replies: 5
    Last Post: 12-12-2003, 06:36 PM

Tags for this Thread