Sorting a 2-dimensional char Array?

I need some sample code that will show me how to sort a two-dimensional character array. Nothing fancy. I just have an array of names I want in  alphabetical order. char Names[9][33];
scully12Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
nietodConnect With a Mentor Commented:
Just use the qsort() function.

example follows.
0
 
chensuCommented:
int compare(const void *elem1, const void *elem2)
{
    return strcmp((const char *)elem1, (const char *)elem2);
}

const int x = 9, y = 33;

char Names[x][y];

//...

qsort(Names, x, y, compare);
0
 
nietodCommented:
int CmpFun(const void *P1,const void *P2)
{
   return strcmp((char *)P1,(char *)P2);
};



char Names[9][33];

qsort(Names,33,9,CmpFun);
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
jasonclarkeCommented:
one other thing you might consider, especially if you want to do anything else with the data is to read it into some more capable data structures, e.g. using the STL:

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

char Names[9][33];

vector<string>  svec;
for (int i=0; i<9; i++)
{
    svec.push_back(Names[i]);
}

std::sort(svec.begin(), svec.end());

....
0
 
nietodCommented:
Probably not in keeping with the "nothing fancy" part of the question, but fancy is worth considering...
0
 
jasonclarkeCommented:
maybe you're right, it just depends on what is wanted next.  I would rather have a vector of strings than a C array of char*s for most purposes.

Also note that in terms of lines of code written (if you exclude the #includes) its about the same.
0
 
nietodCommented:
I agree totally.  There is no question that I would do it that way (Unless I needed non-C++ compatibility.)
0
 
chensuCommented:
nietod,

Just noticed that your code

qsort(Names,33,9,CmpFun);

should read

qsort(Names,9,33,CmpFun);
0
 
nietodCommented:
Opps.
0
All Courses

From novice to tech pro — start learning today.