Home > OS >  Arrange one array and other array do the same
Arrange one array and other array do the same

Time:10-02

sorry if English no good, but I have questions please: I have this array[quantity] that I will sort:

int main() {
     int numberOfFruits[] = {3, 5, 2, 4, 1};
     //I do sorting algorithm
}

but I also want other array do same thing and match.

     char fruits[] = {"apple", "orange", "bannana", "peach", "watermelon"};

So after algrithm it will be:

     int numberOfFruits[] = {1, 2, 3, 4, 5};
     char fruits[] = {"watermelon", "banana", "apple", "peach", "orange"};

How I do this? Thank you.

CodePudding user response:

First, a variable of type char is not able to hold a string (unless it holds the value 0, then it is an empty string). A string is a sequence of char, where the last char has the value 0. Typically a string is stored in an array, or you use a pointer char * to point to a string that is stored somewhere else. In your case, the name of the fruits are stored in a string literal, so you can use a char * to that. An since you want an array of strings, you should declare an array of char *:

char *fruits[] = {.....};

Now to your actual question:

When you have multiple things that belongs together, you can aggregate them together by declaring a struct:

struct fruit
{
   int number;
   char *name;
};

And you can define an array of struct fruit like this:

struct fruit fruits[] = 
  { 
     {1, "watermelon"},
     {2, "banana"},
     {3, "apple"},
     {4, "peach"},
     {5, "orange"}
  }

When you now swap two element of fruits, you swap both number and name together:

 /* Swap the i-th and j-th element in fruits */
 struct fruit tmp = fruits[i];
 fruits[i] = fruits[j];
 fruits[j] = tmp;
  • Related