Thread: I need help with sorting a simple structure please

  1. #1
    Registered User
    Join Date
    Apr 2003

    Unhappy I need help with sorting a simple structure please

    In my program I have an array of the structure CD. (shown below). I am a beginner and I'm having difficultly writing a basic sorting function which will rearrange the 5 CD structures using the 'MNumber' member.

    I understand that I may need to make a temporary copy of my array of structures so that the 'swaping' can occur and the arrays can be placed ascending order based on the 'MNumber' member. I know it's not a lengthly piece of code to do this, but my attempts have been unsucessful. Can anyone help? I'd really appreciate it!

    char MTitle[50];
    int MNumber;
    } CD[5];

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    First off, if you need to make a temporary variable (a seperate instance of your structure) then you'll need to actually give your structure a name.
    struct cdInfo
        ...stuff here...
    } CD[5];
    Now what you have done is created a structure named "cdInfo", and then created an array of five of these structures. You can omit the name as you originally did, but in doing so, you have an unnamed structure.

    If you have an unnamed structure, you cannot create seperate instances of it. By providing a name for your structure, you can now create seperate instances of it:
    struct cdInfo  oneCD;
    Now you can do things with the individual elements of the structure:
    struct cdInfo oneCD;
    oneCD.MNumber = 10;
    strncpy( oneCD.MName, "My CD", 50 );
    Now you've assigned a value to the CD number, and you've copied a name into the name field.

    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Thank you for your help, i will give a go at doing a swap program.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 02-14-2006, 09:04 AM
  2. Request for comments
    By Prelude in forum A Brief History of
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  3. Structure Within Structure
    By Shakira in forum C Programming
    Replies: 3
    Last Post: 11-04-2003, 03:35 PM
  4. sorting a structure of arrays
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 03-15-2002, 11:45 AM
  5. Simple File Creation Algorithm
    By muffin in forum C Programming
    Replies: 13
    Last Post: 08-24-2001, 03:28 PM