Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. /* Example: bubble sort strings in array */
  2.  
  3. #include <stdio.h>  /* Need for standard I/O functions */
  4. #include <string.h> /* Need for string functions */
  5. #include <stdlib.h>
  6.  
  7. #define NUM 25   /* number of strings */
  8. #define LEN 1000  /* max length of each string */
  9.  
  10. int main()
  11. {
  12.   char* Strings[NUM];
  13.   char temp[LEN];
  14.   int length;
  15.  
  16.   printf("Please enter %d strings, one per line:\n", NUM);
  17.  
  18.   /* Write a for loop here to read NUM strings, using fgets(). */
  19.  
  20.   for (int i=0; i < NUM; i++) {
  21.  
  22.     /* Read one line of input into a temp string that is long enough (LEN long) */
  23.  
  24.     fgets(temp, LEN, stdin);
  25.     length = strlen(temp - 1);
  26.  
  27.  
  28.     /* Allocate memory space for String[i] that is only large enough to copy the
  29.        string just read into it.  Suppose the length of the string read into
  30.        temp is "length", then you can use the following: */
  31.  
  32.     Strings[i] = malloc(length+1); /* Plus one for the NULL at end */
  33.     strcpy(*(Strings + i), temp);
  34.   }
  35.  
  36.   puts("\nHere are the strings in the order you entered:");
  37.  
  38.   /* Write a for loop here to print all the strings. */
  39.  
  40.   for(int l = 0; l < NUM; l++)
  41.   {
  42.     printf("%s", Strings[l]);
  43.   }
  44.   for(int o = 0; o < NUM; o++)
  45.   {
  46.     for(int y = 0; y < NUM - 1; y++)
  47.     {
  48.       if(strcmp(Strings[y], Strings[y+1]) > 0)
  49.       {
  50.         int length = strlen(Strings[y+1]);
  51.         char temp[1][length];
  52.  
  53.         //swap function
  54.         temp[0] = *Strings[y+1];
  55.         *Strings[y+1] = *Strings[y];
  56.         *Strings[y] = temp[0];
  57.        }
  58.     }
  59.   }
  60.  
  61.  
  62.   /* Output sorted list */
  63.  
  64.   puts("\nIn alphabetical order, the strings are:");    
  65.   /* Write a for loop here to print all the strings. */
  66.  
  67.  
  68.   /* Write a loop here to use free() to free up space allocated
  69.      for all of the strings above.  */
  70.  
  71.   for(int p = 0; p < NUM; p++)
  72.   {
  73.     printf("%s", Strings[p]);
  74.     free(Strings[p]);
  75.   }
  76.  
  77.   return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement