title: Sorting array of c strings alphabetically
body: <p>I have a homework problem I'm having bit of a problem with, I'm asked to sort an array of C strings alphabetically using C++, sorting algo used must be bubble sort. What I've done so-far (replicated below) can sort the array but only based on the first alphabet. How do I further sort strings the strings with the same initial alphabet ?</p>
  
  <pre><code>&lt;snipped&gt;@arch:~/College/OOP/Lab/W3$ cat 2.cpp
  
  /*
   * Write a function which sorts an array of C strings in ascending order using bubble sort. The
   * number of strings in the array and the array must be passed as parameters to the function
   */
  
  #include &lt;iostream&gt;
  #include &lt;cstring&gt;
  
  using namespace std;
  
  void sort(char **sar, unsigned num, unsigned len)
  {
      char *temp = new char[len];
  
      if (temp == NULL)
      {
          cout &lt;&lt; "\nOut-Of-Memory\n";
          return;
      }
  
      for (unsigned a = 0; a &lt; num-1; a++)
      {
          for (unsigned b = 0; b &lt; ((num-a)-1); b++)
          {
              if (sar[b][0] &gt; sar[b+1][0])
              {
                  strcpy(temp, sar[b]);
                  strcpy(sar[b], sar[b+1]);
                  strcpy(sar[b+1], temp);
              }
          }
      }
  
      delete[] temp;
  }
  
  int main(int argc, char *argv[])
  {
      char **sar;
      unsigned num;
      unsigned len;
  
      cout &lt;&lt; "Number of Strings: ";
      cin  &gt;&gt; num;
      cout &lt;&lt; "Length of Strings: ";
      cin  &gt;&gt; len;
  
      cin.ignore(); // Flush buffer to fix a bug (getline after cin).
  
      sar = (char **) new char*[num];
      if (sar == NULL)
      {
          cout &lt;&lt; "\nOut-Of-Memory\n";
          return -1;
      }
  
      for (unsigned i = 0; i &lt; num; i++)
      {
          sar[i] = (char *) new char[len];
          if (sar[i] == NULL)
          {
              // Let's pretend we 'know' memory management
              // because obviously modern OSs are incapable
              // of reclaiming heap from a quitting process..
              for (unsigned j = 0; j &lt; i; j++)
                  delete[] sar[j];
              cout &lt;&lt; "\nOut-Of-Memory\n";
              return -1;
          }
      }
  
      for (unsigned x = 0; x &lt; num; x++)
          cin.getline(&amp;sar[x][0], 512);
  
      sort(sar, num, len);
  
      cout &lt;&lt; '\n';
      for (unsigned y = 0; y &lt; num; y++)
          cout &lt;&lt; sar[y] &lt;&lt; '\n';
  
      for (unsigned z = 0; z &lt; num; z++)
          delete[] sar[z];
      delete[] sar;
  
      return 0;
  }
  </code></pre>