Pointers to pointers to strings

This is a discussion on Pointers to pointers to strings within the C Programming forums, part of the General Programming Boards category; Okay... I can get the following bubble sort algorithm working perfectly from within main, but since it's used 3 times ...

  1. #1
    Registered User Natase's Avatar
    Join Date
    Aug 2001
    Posts
    123

    Question Pointers to pointers to strings

    Okay... I can get the following bubble sort algorithm working perfectly from within main, but since it's used 3 times I'm trying to give the sort its own function.

    This just keeps on crashing (I know its the strcmp line) and I've tried every combination of '*'s and '&'s I can think of... any ideas?

    void sort_list(char **list, int no_of_words) {
    char *temp_pointer;
    int i=0, compare=0;
    for (i=0;i<no_of_words;i++) {
    compare=strcmp(list[i]), list[i+1]);
    if (compare > 0) {
    temp_pointer=list[i+1];
    list[i+1]=list[i];
    list[i]=temp_pointer;
    }
    }
    }

    P.S. list is an array of pointers to strings declared in main as "char *list[1000]"

    Thanks...

  2. #2
    Registered User Natase's Avatar
    Join Date
    Aug 2001
    Posts
    123
    Excuse the typo in the strcmp line ( a relic of me messing around with it before I posted it)

    it should read:

    compare=strcmp(list[i], list[i+1]);

    Thanks...

  3. #3
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,853
    When the loop counter i = no_of_words you are trying to compare the no_of_words+1 element. ie the array is going out of the allocated memory.

    The array starts at zero so if i==1, you are looking at the 2nd element of the array.

    Use

    for(i=0;i<no_of_words-1;i++)
    and test [i] vs [i+1]
    or

    for(i=1;i<no_of_words;i++)
    and test [i-1] vs [i]

    and all could be well.

    Watch the value in the array in the debugger or print to screen to ensure the strings are passed into the compare/sort correctly.
    Last edited by novacain; 09-17-2001 at 11:35 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using Pointers With Strings
    By bobthebullet990 in forum C Programming
    Replies: 2
    Last Post: 02-14-2006, 05:28 AM
  2. Problems with strings as key in STL maps
    By all_names_taken in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 10:34 AM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM
  4. pointers to strings
    By LiLgirL in forum C Programming
    Replies: 3
    Last Post: 04-23-2004, 02:38 PM
  5. More on pointers and strings
    By mart_man00 in forum C Programming
    Replies: 4
    Last Post: 02-10-2003, 05:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21