Thread: beginners problem - trying to flip a string using pointers.

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    4

    beginners problem - trying to flip a string using pointers.

    Having some trouble with basic stuff while learning C. might seem foolish, but I hope somone can help me see my mistakes.

    my purpose was to flip the pointing order, so it would point to the string from the end to the start. didn't work so well using **str as well.

    Code:
    #include <stdio.h>
    #include <conio.h>
    
    
    
    
    char str_inve(char *ptr);
    
    
    
    
    
    
    char str_inve(char *ptr) /*a function that is supposed to be pointer - based, and to flip a string, and to return a pointer to the flipped string*/
            {
    char *str;
    
    
            for(;*(ptr+1);ptr++); 
    for (;*ptr;str = ptr, ptr--,str++); /*here is the problem. i can't use *str = *ptr, and this seems to be the only available syntax to use. the str = ptr seems to act like an array, and every time
                                         the loop continues the former values erase (*str). */
         for(;*(str-1);str--)
    printf("%c",*(str-1));
                return(*str);
         }
    
    
         void main (void)
    {
    int i;
    str_inve("hello");
    scanf("%d",&i); /*irrelevant*/
         }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    "flip a string" is not standard terminology. Do you mean to reverse a string?

    If inve stands for invert, why not spend the extra two characters to make that explicit. Or call it str_reverse.

    You need to fix your indentation. It's all over the place.

    main should be defined to return an int and should have a "return 0;" statement at the end.

    Since you're not using conio.h (and should avoid it), why not remove the include for it.

    If you want a for-loop to have an empty body, make it more obvious by putting the semicolon, indented, on the next line.

    Please fix those things and re-post.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The second for loop makes no sense.

    Unlike searching forwards, where there is a \0 to mark the end of the string, there is no beginning of string marker.

    Keep the input parameter constant. If you want to chase back and forth over the length of the string, then use a separate copy of the input pointer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Sep 2013
    Posts
    4
    Thanks for the help and yes - I do mean to reverse a string. I tried to change some of it according to what you said. Salem, didn't understand your last remark though - you wanted me to make another copy of *ptr? isn't the input pointer copied in the memory when the function starts?

    Anyway - this is the new code:

    Code:
    #include <stdio.h>
    
    
    char str_invert(char *ptr);
     
    
    
    char str_invert(char *ptr)                  /*a function that is supposed to be pointer - based, and to flip a string, and to return a pointer to the reversed string*/
    
    
    {
    char *str;
    for(;*(ptr+1);ptr++)                        /*moving the pointer to its end*/
    			; 
    for(;*ptr;ptr--, str++)                     /*loop that moves the pointer from the end to the start, and moves the target pointer forward*/ 
    	{str = ptr;}                            /*this doesn't work - wanted to change the value's of *str so it would be the same as *ptr but reversed*/ 
    
    
    for(;*str;str--)                            /*loop that moves the target pointer from the end to the start*/
    			;
    
    
    return(*str);
    }
     
     
         int main (void)
    {
    int i;
    
    
    str_invert("hello");
    
    
    return(0);
    
    
    
    
    }
    Last edited by tomk2005; 09-12-2013 at 03:41 PM.

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think the point is if you wanted to work backwards you would need a copy of the pointer.
    Code:
    	const char *p;
    	for ( p = s + strlen( s ) - 1; p >= s; --p ) putchar( *p );
    It's because the pointer that you past in will serve as a stopping point.

  6. #6
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Assuming that str_invert() is supposed to reverse a string in place, it doesn't need to return a pointer, but if it does return a pointer it needs to return the original pointer.

    The first loop is correct, you need to get a pointer to the end of the string.

    The problem after this is do you understand how to reverse a string? You need to exchange characters in the string to move them around, and you'll need a temporary character variable to exchange characters, similar to temp = a, a = b, b = temp.

    Try working out the logic with a small example string like "1234567". What characters need to be exchanged to reverse the string?
    Last edited by rcgldr; 09-12-2013 at 05:17 PM.

  7. #7
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Since the op hasn't replied to this thread in a while, here is an example program that I wanted to get archived in this thread:

    Code:
    #include <stdio.h>
    
    char * str_reverse(char *ptr)
    {
    char * right, * left;
    char tmp;
    
        if(NULL == (right = left = ptr))
            return(ptr);
        while(*++right);            /* set right to last character */
        right--;
        while(right > left){        /* swap left / right side of string */
            tmp    = *left;
            *left  = *right;
            *right = tmp;
            left++;
            right--;
        }
        return(ptr);                /* return original ptr */
    }
    
    int main ()
    {
    char str[] = "this is a test";
        printf("%s\n", str_reverse(str));
        return(0);
    }

  8. #8
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Quote Originally Posted by rcgldr View Post
    Since the op hasn't replied to this thread in a while, here is an example program that I wanted to get archived in this thread
    What if the string is the null string? (Not a NULL pointer, but a char * pointer to an ascii nul.) Your ++right will step right over it off into ... who knows where.

    I wrote it similarly like so:
    Code:
    #include <stdio.h>
    
    char *str_reverse(char *str)
    {
        char *front, *back;
    
        if (!str || !*str)
            return str;
     
        for (back = str; *back; back++)
            ;
    
        for (front = str, --back; front < back; ++front, --back)
        {
            char t = *front;
            *front = *back;
            *back  = t;
        }
    
        return str;
    }
    
    int main(void)
    {
        char str[] = "hello world";
        puts(str_reverse(str));
        return 0;
    }
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  9. #9
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by oogabooga View Post
    What if the string is the null string?
    I back up these example programs, but in this case I backed up in the wrong direction and copied an old file over the new file that checked for both. With visual studio, printf("%s\n", NULL) will not abort the program but instead display <null>. I'm not sure about other compilers. The "refixed" version is basically the same as yours, but your for loop method is more compact that the expanded while loop I used.

    Code:
    #include <stdio.h>
    
    char * str_reverse(char *ptr)
    {
    char *right, *left;
    char tmp;
    
        if(!ptr || !*ptr)           /* return if null ptr or string */
            return(ptr);
        right = left = ptr;         /* set left and right ptrs */
        while(*++right);            /* set right to last character */
        right--;
        while(right > left){        /* swap left / right side of string */
            tmp    = *left;
            *left  = *right;
            *right = tmp;
            left++;
            right--;
        }
        return(ptr);                /* return original ptr */
    }
    
    int main ()
    {
    char str[] = "this is a test";
        printf("%s\n", str_reverse(str));
        return(0);
    }
    Last edited by rcgldr; 09-15-2013 at 02:04 AM.

  10. #10
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    Humm, how about:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void *memrev(void *to, size_t n, size_t size, const void *from)
    {
    	while (n) {
    		memcpy((char *) to + --n * size, from, size);
    		from = (char *) from + size;
    	}
    	return to;
    }
    
    char *strrev(char *to, const char *from)
    {
    	size_t n = strlen(from);
    
    	to[n] = '\0';
    	return memrev(to, n, 1, from);
    }
    
    int main(void)
    {
    	char buf[80];
    
    	puts(strrev(buf, "this is a test"));
    }

  11. #11
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by Barney McGrew View Post
    Humm, how about ... produce a reversed copy of a string
    The goal was to reverse a string in place, not make a copy. This also means that the reverse function can't be used on a literal string, since it's swapping in place. I think the main point of this problem was using pointers instead of indexing to swap data.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 5 Common Mistakes Beginners Make With Pointers C
    By stahta01 in forum C Programming
    Replies: 7
    Last Post: 08-08-2011, 01:39 AM
  2. A beginners problem.
    By Spazmotic in forum C++ Programming
    Replies: 2
    Last Post: 03-05-2010, 04:52 PM
  3. Clearing Buffer Problem (beginners Q)
    By Iconate in forum C Programming
    Replies: 5
    Last Post: 03-18-2008, 01:57 PM
  4. Beginners - Problem
    By Yuushi in forum C Programming
    Replies: 5
    Last Post: 10-09-2007, 10:08 AM