Thread: Using dynamically allocated strings to sort words

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    9

    Using dynamically allocated strings to sort words

    Here are the instructions:

    Write a program that sorts a series of words entered by the user:

    Enter word: foo
    Enter word: bar
    Enter word: baz
    Enter word: quux
    Enter word:

    In sorted order: bar baz foo quux

    Assume that each word is no more than 20 characters long. Assume there are no more than 50 words to be sorted. Stop reading when the user enters an empty word (i.e., press Enter without entering a word). Store each word in a dynamically allocated string, using an array of pointers to keep track of the strings. After all the words have been read, sort the array and then print the words in a sorted order.

    Hint:
    1) Use the read_line function (textbook, page 287 or slide 20, July 2 lecture) to read each word.
    2) Use qsort function in <stdlib.h> to sort an array of strings.

    I have been getting the following error and warning when I attempt to compile:

    sort_words.c:18: error: invalid operands to binary *
    sort_words.c:30: warning: comparison between pointer and integer

    Where exactly did I go wrong? What do I have to do to get the words to sort in order?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #define WORD_LEN 50
    #define WORD_LIMIT 20
    
    int read_line(char str[], int n);
    
    int int_compare(const void* p, const void* q);
    
    int main()
    {
    char n[WORD_LIMIT];
    int i;
    int *a;
    
    a = malloc(n * sizeof(char));
    
    for(i = 0; i < WORD_LEN; i++)
    {
    printf("Enter a word: ");
    scanf("%c", &n[i]);
    } 
    
    qsort(n, WORD_LEN, sizeof(char), int_compare);
    
    printf("In sorted order:\n");
    
    for(i = 0; i < n; i++)
    printf("%c\t", a[i]);
    
    printf("\n");
    
    return 0;
    }
    
    int int_compare(const void* p, const void* q){
    
    int n1 = *(int *) p;
    int n2 = *(int *) q;
    
    if (n1 < n2)
    return -1;
    
    if (n1 == n2)
    return 0;
    
    return 1;
    }
    
    
    
    int read_line(char str[], int n)
    {
    int ch, i = 0;
    while ((ch = getchar()) != '\n') {
    if (i < n)
    str[i++] = ch;
    }
    str[i] = '\0';
    return i;
    }

  2. #2
    Webhead Spidey's Avatar
    Join Date
    Jul 2009
    Posts
    285
    Well, your first problem is that malloc expects the size of the number of bytes it should allocate as a parameter and you are passing in a memory address.

    Code:
    a = malloc(n * sizeof(char));
    This statement is meaningless since 'n' is a pointer which points to the address of the first element in the char array.

    To allocate the proper number of bytes, you will have to give it a size

    Code:
    a = malloc(WORD_LIMIT * sizeof(char));
    This will allocate 20 bytes of memory and return a pointer to that memory.

    Your next mistake at line 30 is similar

    Code:
     for(i = 0; i < n; i++)
    n is a pointer so this statement is again meaningless. Instead you want to check if i < WORD_LIMIT .
    Last edited by Spidey; 07-12-2009 at 08:36 PM.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    9
    It is compiling, but it still is not working properly. If I enter a word, weird output comes up, and it does not stop once you press enter.

    Here is what I get:

    Enter a word: boo
    Enter a word: Enter a word: Enter a word: Enter a word:


    Here is my code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
            
    int int_compare(const void* p, const void* q);
            
    int main()
    {
            int n, i;
            int *a;
            
            printf("Enter the length of the array: ");
            scanf("%d", &n);
     
            a = malloc(n*sizeof(int));
    
    for(i = 0; i < n; i++)
            {
                    printf("Enter a number: ");
                    scanf("%d", &a[i]);
            }   
       
            qsort(a, n, sizeof(int), int_compare);
    
            printf("In sorted order:\n");
    
            for(i = 0; i < n; i++)
                    printf("%d\t", a[i]);
    
            printf("\n");
    
            return 0;
    }
    
    int int_compare(const void* p, const void* q){
    
    int n1 = *(int *) p;
     n1 = *(int *) p;
    int n2 = *(int *) q;
                    
    if (n1 < n2)
       return -1;
            
    if (n1 == n2)
        return 0;
    
    return 1;
    }
     
            
    int read_line(char str[], int n)
    {
      int ch, i = 0;
      while ((ch = getchar()) != '\n') {
        if (i < n)
          str[i++] = ch;
      }
      str[i] = '\0';
      return i;     
    }

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Spidey View Post
    To allocate the proper number of bytes, you will have to give it a size

    Code:
    a = malloc(WORD_LIMIT * sizeof(char));
    This will allocate 20 bytes of memory and return a pointer to that memory.
    This would be better written as:
    Code:
    a = malloc( WORD_LIMIT * sizeof *a );
    Now you don't actually have to add the size multiplier for char, but in the event you changed your type later on, the above would save you some trouble.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Webhead Spidey's Avatar
    Join Date
    Jul 2009
    Posts
    285
    Quote Originally Posted by TampaTrinDM88 View Post
    It is compiling, but it still is not working properly. If I enter a word, weird output comes up, and it does not stop once you press enter.

    Here is what I get:

    Enter a word: boo
    Enter a word: Enter a word: Enter a word: Enter a word:


    Here is my code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
            
    int int_compare(const void* p, const void* q);
            
    int main()
    {
            int n, i;
            int *a;
            
            printf("Enter the length of the array: ");
            scanf("%d", &n);
     
            a = malloc(n*sizeof(int));
    
    for(i = 0; i < n; i++)
            {
                    printf("Enter a number: ");
                    scanf("%d", &a[i]);
            }   
       
            qsort(a, n, sizeof(int), int_compare);
    
            printf("In sorted order:\n");
    
            for(i = 0; i < n; i++)
                    printf("%d\t", a[i]);
    
            printf("\n");
    
            return 0;
    }
    
    int int_compare(const void* p, const void* q){
    
    int n1 = *(int *) p;
     n1 = *(int *) p;
    int n2 = *(int *) q;
                    
    if (n1 < n2)
       return -1;
            
    if (n1 == n2)
        return 0;
    
    return 1;
    }
     
            
    int read_line(char str[], int n)
    {
      int ch, i = 0;
      while ((ch = getchar()) != '\n') {
        if (i < n)
          str[i++] = ch;
      }
      str[i] = '\0';
      return i;     
    }
    Firstly, I dont see "Enter a Word" anywhere in this version of your code. All I see is "Enter a number", which is doing exactly what your telling it to do..

    Code:
     for(i = 0; i < n; i++)
            {
                    printf("Enter a number: ");
                    scanf("%d", &a[i]);
            }
    What your code translates to is :

    Ask the user for a number until the length of the array is reached and assign that number to the i'th element of the dynamic array a.
    After that you call qsort on that array and display the results.

    Now just replace the int with a version that would work for strings and your done.

    Hint: You might want to replace int_compare with sting_compare and use the readline function at your disposal.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamically allocated strings??
    By CS_Student8337 in forum C Programming
    Replies: 18
    Last Post: 03-19-2009, 05:14 AM
  2. Replies: 2
    Last Post: 11-26-2008, 10:25 AM
  3. scope of dynamically allocated variables
    By lanzyzhang in forum C Programming
    Replies: 4
    Last Post: 07-20-2004, 10:59 AM
  4. delete dynamically allocated char array
    By xddxogm3 in forum C++ Programming
    Replies: 7
    Last Post: 11-23-2003, 04:57 PM
  5. Splitting strings into words.
    By 0x7f in forum C++ Programming
    Replies: 6
    Last Post: 03-31-2003, 03:49 PM