0

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++;
   }
}
2
  • 1
    What line does the error occur on? Why do you think this happens? What type is lastName? Commented Dec 5, 2012 at 20:28
  • 2
    What does StudentRecord look like? If .lastName is a char[] you can't assign it like that. You need to use strcpy() or similar to move the bytes from one block to the other. Commented Dec 5, 2012 at 20:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.