alphabetizing an array of strings

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 4181 Views - Last Post: 22 October 2010 - 05:24 PM Rate Topic: -----

#1 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

alphabetizing an array of strings

Posted 21 October 2010 - 01:19 PM

hello,

[for C]

i'm trying to write a function called:
void first_last( char *s[], int n, char **first, char **last )

given an array s of n strings, it is supposed to find the first and last string in the array according to alphabetical order and then store those values into **first and **last.

i have to use the function on an array of 8 words afterwards.

____

i am trying to figure out how to go about this but it's so difficult for me to wrap my head around pointers to pointers. i understand that char*s will point to the first string in the array of strings, and that char **s will point to the first letter in the first word in the array of strings.

but i do NOT understand how i can go about testing every first letter of every first word. i know you can increment a pointer like ++char* in order to move to the second word, but how can i go about comparing the first letter in every word for 8 words? is it possible to do something like char*[n] in order to reference the nth string in my array of n strings?

can someone please give me some guidance on how to start thinking about this?

thanks!

-mrd

This post has been edited by mrdmrd: 21 October 2010 - 01:20 PM


Is This A Good Question/Topic? 0
  • +

Replies To: alphabetizing an array of strings

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,516
  • Joined: 23-August 08

Re: alphabetizing an array of strings

Posted 21 October 2010 - 01:27 PM

A quick example:

#include <stdio.h>

int main(void)
{
    const char *shakespeare[] = { "All", "the", "world's", "a", "stage" };
    int i = 0;
    for (; i < sizeof(shakespeare)/sizeof(*shakespeare); ++i)
        printf("%c ", shakespeare[i][0]);
    printf("\n");

    return 0;
}


Was This Post Helpful? 0
  • +
  • -

#3 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 21 October 2010 - 01:32 PM

thanks but do you think you could explain? i dont understand exactly what is going on.

View Postmrdmrd, on 21 October 2010 - 12:19 PM, said:

hello,

[for C]

i'm trying to write a function called:
void first_last( char *s[], int n, char **first, char **last )

given an array s of n strings, it is supposed to find the first and last string in the array according to alphabetical order and then store those values into **first and **last.

i have to use the function on an array of 8 words afterwards.

____

i am trying to figure out how to go about this but it's so difficult for me to wrap my head around pointers to pointers. i understand that char*s will point to the first string in the array of strings, and that char **s will point to the first letter in the first word in the array of strings.

but i do NOT understand how i can go about testing every first letter of every first word. i know you can increment a pointer like ++char* in order to move to the second word, but how can i go about comparing the first letter in every word for 8 words? is it possible to do something like char*[n] in order to reference the nth string in my array of n strings?

can someone please give me some guidance on how to start thinking about this?

thanks!

-mrd

This post has been edited by mrdmrd: 21 October 2010 - 01:33 PM

Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,516
  • Joined: 23-August 08

Re: alphabetizing an array of strings

Posted 21 October 2010 - 02:14 PM

I'm not trying to do the assignment for you, but explain a bit about how pointers work. Here's an expanded and fully-commented program:
#include <stdio.h>

int main(void)
{
    /* An array of const char *s, each of which points to a word */
    const char *shakespeare[] = { "All", "the", "world's", "a", "stage" };
    size_t i = 0;

    /* Here's the size of the array, and each element */
    printf("Size of the array: %lu\n", sizeof(shakespeare));
    printf("Size of each element in the array: %lu\n",
           sizeof(*shakespeare));
    /*                                                                          
       The number of words is determined by taking the size of the array,       
       which is the number of elements times the size of a char *, and          
       dividing by the size of the first element, which is                      
       a char *. The size of a character pointer is 8 on my system.             
       Because the sizeof operator is a compile-time operator, this             
       only works for arrays which have dimensions at compile time.              
    */
    size_t number_of_words = sizeof(shakespeare)/sizeof(*shakespeare);
    for (; i < number_of_words; ++i)
    {
        /*                                                                      
           For clarity, I will create a temporary variable pointing             
           to the word we are current pointing at.                              
         */
        const char *word = shakespeare[i];

        /*                                                                      
           Let's print the address of each word. This generates                 
           a warning, but I figure you don't want to see the                    
           hexadecimal address we would normally display.                       
           Notice how it changes by the size of the pointer                     
           as printed above?                                                    
        */
        printf("Word %s is at %lu\n", word, &shakespeare[i]);
    }

    for (i = 0; i < number_of_words; ++i)
    {
        const char *word = shakespeare[i];
        /*                                                                      
           The first character in a character array is the one at               
           the 0th index, because arrays are indexed from 0 -> size - 1.        
           Because the value of an array is a pointer to its first              
           element, you can also use the pointer dereference operator,          
           *, to access it. I'll demonstrate both methods.                      
        */
        if (i % 2 == 0)
            printf("%c ", word[0]);
        else
            printf("%c ", *word);
    }
    printf("\n");

    return 0;
}



Some more info from memory in the debugger:
(gdb) p shakespeare 
$1 = {0x100000ec0 "All", 0x100000ec4 "the", 0x100000ec8 "world's", 0x100000ed0 "a", 0x100000ed2 "stage"}


Those are the const char *s.

Here we are accessing the individual words (the const char * noted above):
(gdb) p shakespeare[0]
$2 = 0x100000ec0 "All"
(gdb) p shakespeare[1]
$3 = 0x100000ec4 "the"
(gdb) p shakespeare[2]
$4 = 0x100000ec8 "world's"
(gdb) p shakespeare[3]
$5 = 0x100000ed0 "a"
(gdb) p shakespeare[4]
$6 = 0x100000ed2 "stage"



Here are the pointers to the char *s:
(gdb) p &shakespeare[0]
$7 = (const char **) 0x7fff5fbff490
(gdb) p &shakespeare[1]
$8 = (const char **) 0x7fff5fbff498
(gdb) p &shakespeare[2]
$9 = (const char **) 0x7fff5fbff4a0
(gdb) p &shakespeare[3]
$10 = (const char **) 0x7fff5fbff4a8
(gdb) p &shakespeare[4]
$11 = (const char **) 0x7fff5fbff4b0



And showing getting the last word. shakespeare[4] gets the pointer to the last word, & gets the ADDRESS of that pointer, and * defreferences that address, that is goes to the location at that address and retrieves the value stored there.
(gdb) p *(&shakespeare[4])
$12 = 0x100000ed2 "stage"


Was This Post Helpful? 0
  • +
  • -

#5 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 22 October 2010 - 09:35 AM

jack,

i sort of follow what you are saying. for this assignment, however, determining the number of words in our array of strings is not necessary as the int n in the function:

void first_last(char*s[], int n, char**first, char**last)

int n will be the number of words in char *s.

i've tried to write a code snippet here to cycle through the n words in array char *s.

for an array of n words (i.e. "hello" "ace" "freeley") the code is supposed to :

1. make a comparison of two words (i.e. "hello" "ace")
2. place alphabetically earlier one in the slot first (i.e. first = ace)
3. move to next word
4. make comparison between "first" and next word (i.e. "ace" "freeley")
5. place alphabetically earlier one into "first" (first = ace)

here is a code snippet. how am i doing? am i thinking about this right?

void first_last(char*s[], int n, char**first, char**last)
{
	int i=1;
	int value;
	int j=1;
	first=&s;							//set pointer first to value of first word in array 
	
	while (i<=n)						//while you have not reached the last string. note: i is a counter and n is number of words in array s
	{
		(*s)++;							//point to the next word
		
	if (strcmp(s,first)<0)				//if "s" (current word pointed at) comes before "first" (highest ranking word alphabetically at the time)  
	{
		first=s							//set first to be 
		s=(*s)++					    //move to the next word in the array (next comparison will be between current first word is the next word)
		
		i++;							//increment counter to keep track of what word in array you are on
	}	

Was This Post Helpful? 0
  • +
  • -

#6 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 22 October 2010 - 10:21 AM

disregard former code. how about this code:

#include <stdio.h>

int main()
{

  char *s[4]={"what", "up", "big", "man"};
  int i= 1;
  int value;
  int j=1;
  char **first;
  int n=4;

  first=&*s;//set pointer first to value of first word in array                                                                           

   while (i<=n)//while you have not reached the last string. note: i is a counter and n is number of words in array s                     
    {
      (*s)++;//point to the next word                                                                                                     

      if (strcmp(s,first)<0)//if "s" (current word pointed at) comes before "first" (highest ranking word alphabetically at the time)     
        {
          //set first to be                                                                                                               
            *first=(*s)++;    //move to the next word in the array (next comparison will be between current first word is the next word)  
        }
            i++;//increment counter to keep track of what word in array you are on                                                        

    }

  printf("%s is the first word \n", first);

            return(0);
}




it compiles and prints

" is the first word."

if only it would put a word in the blank.
Was This Post Helpful? 0
  • +
  • -

#7 mojo666  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 352
  • View blog
  • Posts: 771
  • Joined: 27-June 09

Re: alphabetizing an array of strings

Posted 22 October 2010 - 12:13 PM

The following is based on my knowledge of c++. I'm not sure how much of it also applies to c.

  first=&*s;
  //should be
  first=s;

//you later do this
*first = (*s)++
//this modifies whatever is stored at s[0].  You should give first a new char* to point at so you can copy the contents of s without overwriting them



You seem to be mismatching pointers a lot.
first is a char **
s is a char**
*first and *s are char *'s

(*s)++;//point to the next word

//s is a char **.  *s is a char *.  (*s)++ moves to the next character in a word.
//to refer to the next word, you want to call s[i]

strcmp(s,first)<0)
printf("%s is the first word \n", first);

//s and first are char**'s.  I think you want something like strcmp(*s,*first) and printf("%s is the first word \n", *first)



Commands like (*s)++ when s is your sole reference to an object is a great way to cause memory leaks. Use array notation.
Was This Post Helpful? 0
  • +
  • -

#8 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 22 October 2010 - 12:19 PM

OK folks, i think i am getting closer, but can i get the error "Segmentation Fault Core Dumped" when i run this program.

can anyone tell me why?

#include <stdio.h>

void first_last(char *s[], int n, char **first)
{

  int i= 1;
  int j=1;

  first=&*s;
  printf("%s is the initial testing word \n", *first);

  while (i<n)
    {
      *first++;

      if (strcmp(*s, *first)<0)
        {
          *first=*s;
        }
      i++;

    }
}

int main ( ) {
  char *array [] = { "hello" , "world " , "today" , "is" , " a " , "very" , "nice", "day" }\
 ;
  int size=8;
  char **minS;
  first_last(array, size, minS);
  printf ("The first word is %s and the last is %s \n", minS);
  return(0);
}







Was This Post Helpful? 0
  • +
  • -

#9 mojo666  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 352
  • View blog
  • Posts: 771
  • Joined: 27-June 09

Re: alphabetizing an array of strings

Posted 22 October 2010 - 12:28 PM

View Postmrdmrd, on 22 October 2010 - 11:19 AM, said:

OK folks, i think i am getting closer, but can i get the error "Segmentation Fault Core Dumped" when i run this program.

can anyone tell me why?

  char *array [] = { "hello" , "world " , "today" , "is" , " a " , "very" , "nice", "day" }\
 ;
  int size=8;
  char **minS;


Not sure what happened with the end of the first line, but the seg fault is occuring because you need to allocate an array for minS to point to. You cannot do anything with *minS until minS actually points to something.

EDIT: nevermind. I overlooked first=&*s;

This post has been edited by mojo666: 22 October 2010 - 12:32 PM

Was This Post Helpful? 0
  • +
  • -

#10 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 22 October 2010 - 12:43 PM

if anyone can make this work i will be so eternally grateful.

i get one error message
1: warning: parameter names (without types) in function declaration

my eyes ache. help would be so appreciated.

#include <stdio.h>

void first_last(char *s[], int n, char **first, char **last)

{
	
	int i= 1;
	int j=1;
	
	first=&*s;//set pointer first to value of first word in array                                                                                                                  
	
	while (i<n)//while you have not reached the last string.                                                                           
		
    {
		(first)++;//point to the next word                                                                                                                                         
		
//if "s" (current word pointed at) comes before "first" (highest ranking word alphabetically at the time)
		if (strcmp(*s,*first)<0) 
		{
			                                                                                                                                                     
			*first=*s;    //move to the next word in the array (next comparison will be between curren\                                                                                
			t first word is the next word)
		}
		i++;//increment counter to keep track of what word in array you are on                                                                                                           
		
	}
	
	printf("%s is the smallest word lexicographically \n", *first);
																																												
	last=&*s;//set pointer first to value of first word in array                                                                                                                     
	
	//while you have not reached the last string. note: i is a counter and n is number of words in array s     
	while (j<n)                                                                        
																																							
	{
		(last)++;//point to the next word                                                                                                                                            
		
	//if "s" (current word pointed at) comes before "first" (highest ranking word alphabetically at the time)
		if (strcmp(*s,*last)>0)                                                                                                                                      
        {
						
	//move to the next word in the array (next comparison will be between current first word is the next word	
	
	*last=*s;                                                                                                                                         
		}
		j++;//increment counter to keep track of what word in array you are on                                                                                                           
		
	}
	
	printf("%s is the largest word lexicographically \n", *last);
	
	return;
}

int main()
{
	char *array [] = {"hello", "world", "today", "is", "a", "very", "nice", "day" };
	int size=8;
	char **minS;
	char **maxS;
	void first_last (array, size, minS, maxS);
	printf ("The first word is %s and the last is %s \n", minS, maxS);
	return(0);
	
}



Was This Post Helpful? 0
  • +
  • -

#11 jimblumberg  Icon User is offline

  • member icon


Reputation: 4074
  • View blog
  • Posts: 12,562
  • Joined: 25-December 09

Re: alphabetizing an array of strings

Posted 22 October 2010 - 01:38 PM

What error messages/warnings are you getting?

Please post the complete error messages (the code should not compile as written)..

Jim
Was This Post Helpful? 0
  • +
  • -

#12 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 22 October 2010 - 01:40 PM

i receive the following messages:

blum.c: In function 'main':
blum.c:61: warning: parameter names (without types) in function declaration

EDIT: also, i am able to get it so that i can get the largest word lexigraphically is hello and the smallest is day. i want to alphabetize now though. how can i turn my strcmp comparison to look at the first letter of each word?

but basically, how can i get this to run?


View Postjimblumberg, on 22 October 2010 - 12:38 PM, said:

What error messages/warnings are you getting?

Please post the complete error messages (the code should not compile as written)..

Jim

This post has been edited by mrdmrd: 22 October 2010 - 01:42 PM

Was This Post Helpful? 0
  • +
  • -

#13 jimblumberg  Icon User is offline

  • member icon


Reputation: 4074
  • View blog
  • Posts: 12,562
  • Joined: 25-December 09

Re: alphabetizing an array of strings

Posted 22 October 2010 - 01:43 PM

In your main() you have this:

    
    void first_last (array, size, minS, maxS);



Do you see anything wrong here?

Jim
Was This Post Helpful? 0
  • +
  • -

#14 mrdmrd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 07-October 10

Re: alphabetizing an array of strings

Posted 22 October 2010 - 02:16 PM

yes, that was stupid of me. it's been a day.

but i still would like to know, how can i alter my strcmp function to compare the first letters of each word? cause right now it is not printing out the correct answers.

thanks for your help.
Was This Post Helpful? 0
  • +
  • -

#15 jimblumberg  Icon User is offline

  • member icon


Reputation: 4074
  • View blog
  • Posts: 12,562
  • Joined: 25-December 09

Re: alphabetizing an array of strings

Posted 22 October 2010 - 02:36 PM

View Postmrdmrd, on 22 October 2010 - 02:16 PM, said:

but i still would like to know, how can i alter my strcmp function to compare the first letters of each word? cause right now it is not printing out the correct answers.


When you say "my strcmp function" are you trying to implement a replacement for the standard C function strcmp?

If not please post the code with the section you are talking about highlighted.

Jim

This post has been edited by jimblumberg: 22 October 2010 - 02:37 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2