Flip words in a char array.

This is a discussion on Flip words in a char array. within the C Programming forums, part of the General Programming Boards category; I am curious if I am on the right path of doing what I need to do. I appreciate the ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    42

    Flip words in a char array.

    I am curious if I am on the right path of doing what I need to do. I appreciate the help.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
    	char a[] = "Dog eat Cat";
    	
    	char *b = NULL;
    	char *buffer = NULL;
    	int slen = 0, count = 0, templen = 0;
    	int size = strlen(a);
    	buffer = malloc((strlen(a)+1));
    	b = malloc((strlen(a)+1));
    	printf("First String: %s\n", a); /* Dog eat Cat */
    	buffer = strtok (a," ,.-");
    	while (buffer != NULL)
      	{
    		slen = strlen(buffer);
    		templen = slen;
    		while(buffer[count] != '\0')
    		{
    			b[size-(slen--)]=buffer[count++];
    		}
    		size = size-(templen+1);
    		count = 0;
        	buffer = strtok (NULL, " ,.-");
      	}	
    	printf("Second String: %s\n", b); /* Cat eat Dog */
    	
    	free(b);
    	free(buffer);
    	b = NULL;
    	buffer = NULL;
    
    	return (0);
    }
    output:
    Code:
    First String: Dog eat Cat
    Second String: Cat

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Possibly you could spare us a few sentences to tell us what it is that you are trying to do.

    "Flip" is a little flippant, and non-specific. Flip how? Word1 becomes word3 and the two others words are moved up one place? Alphabetical sort of the words? (ascending or descending). Flip word1 to word2, only? Reverse the order of all the words?

    OK, I see what you're trying to do - clear. I do like to have the problem described in words, however, rather than just buried in code comments, near the bottom of the program.

    Your while loop (inner) relies on an end of string char being at the end of Dog, which is wrong. "Dog eats Cats", is ONE string,and has just ONE end of string char.

    Use the space between words OR the end of string marker, to make it right. There are at least three different ways to do this - so just pick one you like. I'm not going to spell them all out.
    Last edited by Adak; 10-16-2010 at 10:34 AM.

  3. #3
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198
    Code:
    buffer = malloc((strlen(a)+1));
        b = malloc((strlen(a)+1));
    Aside whatever he's trying to do, both buffer and b are intialized
    as type void and they're being assigned to type char.

    Is there something missing in front of malloc? (? *)malloc

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    Quote Originally Posted by Char*Pntr
    Aside whatever he's trying to do, both buffer and b are intialized
    as type void and they're being assigned to type char.
    It is quite clear that they are of type pointer to char and are each assigned a pointer to void as returned by malloc, so there is no problem, other than a failure to check that they are not assigned null pointers. Of course, it is a little pointless to keep on calling strlen(a) when size already contains the desired string length.

    Quote Originally Posted by Char*Pntr
    Is there something missing in front of malloc? (? *)malloc
    If you are thinking of a cast, then no, that is not missing since this is C.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198
    Quote Originally Posted by laserlight View Post
    If you are thinking of a cast, then no, that is not missing since this is C.
    My (C) compiler is complaining about both malloc() statements. But it still compiles.
    Apparently, this was a warning and not an error.

    I'll fix that by turning the warning level down a notch or two.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    Quote Originally Posted by Char*Pntr
    My (C) compiler is complaining about both malloc() statements.
    A little off topic here, but test with this program:
    Code:
    #include <stdlib.h>
    
    int main(void)
    {
        char *p = NULL;
        p = malloc(sizeof(*p));
        free(p);
        return 0;
    }
    If your compiler warns on this (at a suitably high warning level) but is silenced when you explicitly cast the return value of malloc, then it arguably has a bug since an implicit conversion from void* to char* (or any other pointer to object type) is expressly permitted by the C standard.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198
    I got the same error with your code with warnings up high:

    "Error: A value of type "void *" cannot be assigned to an entity of type "char *" "

    This is the 2nd or 3rd time I've been burnt by this msg. I'm using MS VS2010.


    This silenced the error:

    Code:
     p =(char *) malloc(sizeof(*p));
    Sorry, I'm off topic and I'll go to the general forum on this one. Thanks laserlight.

  8. #8
    Registered User
    Join Date
    Jan 2008
    Posts
    42
    Sorry I wasn't too clear on what I want to do. I want to do the following:

    Dog eat Cat -> Cat eat Dog.

    Hello how are you -> you are how Hello

    etc.

    I get no errors or warnings when I compile my code. I'm using gcc on my mac.

    Code:
    gcc experiment2.c -o myprog
    I'm new to C so I had an idea in my head and tried to put into code. I appreciate any help.

  9. #9
    Registered User
    Join Date
    Jan 2008
    Posts
    42
    Quote Originally Posted by laserlight View Post
    It is quite clear that they are of type pointer to char and are each assigned a pointer to void as returned by malloc, so there is no problem, other than a failure to check that they are not assigned null pointers. Of course, it is a little pointless to keep on calling strlen(a) when size already contains the desired string length.
    You mean a check like this:

    Code:
        if (!buffer)
        {
            fprintf(stderr, "FATAL - malloc failed!");
            return(0);
        }

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    Quote Originally Posted by Char*Pntr
    I got the same error with your code with warnings up high:

    "Error: A value of type "void *" cannot be assigned to an entity of type "char *" "

    This is the 2nd or 3rd time I've been burnt by this msg. I'm using MS VS2010.
    My guess is that you are compiling as C++ instead of compiling as C.

    Quote Originally Posted by mherald81
    I want to do the following:

    Dog eat Cat -> Cat eat Dog.

    Hello how are you -> you are how Hello

    etc.
    Right. Looking at your current code, are you trying to do this by populating the destination string from the back? That is, you copy Dog to the end of the destination string, prepend a space, then copy eat, prepend a space, and then copy Cat?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Jan 2008
    Posts
    42
    Quote Originally Posted by laserlight View Post
    Right. Looking at your current code, are you trying to do this by populating the destination string from the back? That is, you copy Dog to the end of the destination string, prepend a space, then copy eat, prepend a space, and then copy Cat?
    Yes, that's what I'm trying to do.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    I believe that that can work. I suggest keeping track of the beginning of the destination string. Take care how you write the space that separates the token.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Jan 2008
    Posts
    42
    Quote Originally Posted by laserlight View Post
    I believe that that can work. I suggest keeping track of the beginning of the destination string. Take care how you write the space that separates the token.
    Thanks for the hint! I got it, simple fix.

  14. #14
    Registered User
    Join Date
    Jan 2008
    Posts
    42
    Here's my final edits to get it working.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char a[] = "Dog eat Cat";
        
        char *b = NULL;
        char *buffer = NULL;
        int slen = 0, count = 0, templen = 0;
        int size = strlen(a);
        buffer = malloc((size+1));
        int i;
    
        if (!buffer)
        {
            fprintf(stderr, "FATAL - malloc failed!");
            return(0);
        }
        b = malloc((size+1));
        if (!b)
        {
            fprintf(stderr, "FATAL - malloc failed!");
            return(0);
        }
        for(i = 0; i<=size; i++)
        {
            b[i] = ' ';
        }
        
        printf("First String: %s\n", a); /* Dog eat Cat */
        buffer = strtok (a," ,.-");
        while (buffer != NULL)
          {
            slen = strlen(buffer);
            templen = slen;
            while(slen != 0)
            {
                b[size-(slen--)]=buffer[count++];
                
            }
            size = size-(templen+1);
            count = 0;
            buffer = strtok (NULL, " ,.-");
          }    
    
        printf("Second String: %s\n", b); /* Cat eat Dog */
        
        free(b);
        free(buffer);
        b = NULL;
        buffer = NULL;
    
        return (0);
    }
    Please hit me up with some pointers and other suggestions to make it better.

  15. #15
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Code:
    char *wordrev(char *s,const char *delims)
    {
      char *y=calloc(1,strlen(s)+1);
      char *p=s+strlen(s);
      while( p!=s )
        if( strchr(delims,*--p) )
          strcat(y,p+1),strncat(y,p,1),*p=0;
      if( !strchr(delims,*s) )
        strcat(y,s);
      strcpy(s,y);
      free(y);
      return s;
    }
    
    int main() {
      char a[] = "Dog eat Cat";
      puts( wordrev(a," ,.-") );
      return 0;
    }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sending a simple email in C++?
    By Coukapecker in forum C++ Programming
    Replies: 6
    Last Post: 04-09-2010, 12:36 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. char array of words
    By sujeet1 in forum C++ Programming
    Replies: 5
    Last Post: 05-25-2007, 07:27 AM
  4. Replies: 16
    Last Post: 10-29-2006, 04:04 AM
  5. code condensing
    By bcianfrocca in forum C++ Programming
    Replies: 4
    Last Post: 09-07-2005, 09:22 AM

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