title: using qsort to sort a malloced character array in c
body: <p>This program so far has one purpose, take in two integers(the size of the user defined arrays) and then takes in one element or character at a time and adds them to the array.  Once both arrays are filled, one of the arrays must be alphabetized (I'm attempting to do this with the built in 'qsort').  </p>
  
  <p>However, this code hits a runtime error once the qsort is called, and my problem is I don't know why or how to fix it.</p>
  
  <p>My Code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  
  int toExit(int exit){
      while(exit != 1 || exit !=2){
  
          printf("\n\nPlease Choose:\n1) Exit\n2) Run program again\nYour choice: ");
          scanf("%d", &amp;exit);
          printf("\n");
  
          switch(exit){
          case 1:
              return exit;
          case 2:
              return exit;
          default:
              printf("That is not one of the given options.\n\n");
          }
      }
  
  }    
  
  int compare(const void *a, const void *b){
  
      const char* a1 = *(const char**)a;
      const char* b1 = *(const char**)b;
      return strcmp(a1,b1);
  }  
  
  int main(void) {
  
      int exit=0, i, j;
      int lengthX, lengthA;
      char *Xsequence, *Asequence, *_$;
  
      while(exit != 1){
  
  
      printf("please enter the length of sequence A: ");
      scanf("%d", &amp;lengthA);
      printf("please enter the length of sequence X: ");
      scanf("%d", &amp;lengthX);
  
      printf("\n");  //spacing, visual look of the program
  
      Asequence =(char*) malloc(lengthA*sizeof(char));
      Xsequence =(char*) malloc(lengthX*sizeof(char));
  
      for(j=0;j&lt;=lengthA-1;j++)
      {
          printf("Element %d of A: ",j+1);
          scanf("%s", &amp;Asequence[j]);
      }
  
      printf("Last Element of A (looking for \"$\"): ");
      scanf("%s", &amp;_$);
      printf("\n");  //spacing, visual look of the program
  
      for(j=0;j&lt;=lengthX-1;j++)
      {
          printf("Element %d of X: ",j+1);
          scanf("%s", &amp;Xsequence[j]);
      }
  
      printf("Last Element of X (looking for \"$\"): ");
      scanf("%s", &amp;_$);
      printf("\n");  //spacing, visual look of the program
  
      qsort (Xsequence, lengthX, sizeof(char*), compare);
      printf("The \"A\" sequence is: %s\n",Asequence);
      printf("The \"X\" sequence is: %s\n",Xsequence);
  
  
      exit = toExit(exit);
  
      }
  // return 0; 
  }
  </code></pre>