Evan
Evan

Reputation: 355

Bubble Sorting a string in an Array

I am trying to bubble sort the LastName property (under a struct StudentRecord, hence the names) of an array using bubble sort. But I am having trouble doing so.

I am receiving the error (I'm using MinGW to compile):

Invalid array assignment

Here is my code:

void option2 (StudentRecord student[], int n)
{
   int pass = 1;
   bool done = false;
   StudentRecord temp;
   while (!done && pass <= n-1)
   {
      done = true;
      for (int i = n-1; i >= pass; i--)
      {
         if (student[i].lastName < student[i-1].lastName)
         {
            temp.lastName = student[i].lastName;
            student[i].lastName = student[i-1].lastName;
            student[i-1].lastName = temp.lastName;
            done = false;
         }
      }
      pass++;
   }
}

Upvotes: 0

Views: 1508

Answers (1)

Cameron
Cameron

Reputation: 98756

It looks like lastName is an array of characters.

You can't assign entire arrays to each other; you need to use strcpy() (#include <cstring>) to copy one to the other. Additionally, using < with character arrays will cause the memory addresses of the first elements in each array to be compared, not the entire string of characters; use strcmp for this (which returns < 0 iff the first parameter is lexicographically < the second parameter).

Note you can (and probably should) use std::string instead (#include <string>), which will automatically provide copying, comparison, and dynamic growth for you transparently.

Upvotes: 2

Related Questions