Thread: Word backwards! stupid problem!!!

  1. #1
    Sometimes so stupid... shardin's Avatar
    Join Date
    Jul 2007
    Location
    Dalmatia/CRO
    Posts
    78

    Word backwards! stupid problem!!!

    I forgot how to do it, dont know what is wrong, help! Output is some crap...

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    char *funk(char *);
    int main()
    
    {
    	int sranje;
    	char niz[30];
    	char *n1,*p;
    
    	printf("Recenica: ");
    	gets(niz);
    	n1=(char *)malloc(sizeof(char)*(sizeof(niz)));
    	strcpy(n1,niz);
    	p=funk(n1);
    	printf("&#37;s", p);
    
    	scanf("%d", &sranje);
    }
    
    char *funk(char *n1){
    
    	char *p;
    	int i;
    	p=(char *)malloc(sizeof(char)*(sizeof(n1)));
    
    	for(i=strlen(n1)-1;i==0;i--)
    	{
    		p[i]=n1[i];
    		
    	}
    	return p;
    }
    Last edited by shardin; 09-20-2007 at 11:30 AM.
    ...and aprentice shall become master...or not...

    "Never let your sense of moral prevent you from doing what is right!" Salvor Hardin, mayor of Terminus

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    gets(niz);
    Don't use gets, it's unsafe. Use fgets instead since you can specify a mazimum number of characters to accept from the user.

    Code:
    n1=(char *)malloc(sizeof(char)*(sizeof(niz)));
    First off, you don't need to cast the return value of malloc in C. There is also little reason to malloc a chunk of memory if it's always going to be the same size (30). Maybe you meant:
    Code:
    n1 = malloc(strlen(niz)+1);
    Why have two copies of this word? You already have the initial copy, and the function call is supposed to create another (reversed version). Just use the initial copy to create the reversed version.

    Code:
    p=(char *)malloc(sizeof(char)*(sizeof(n1)));
    Again, you're casting malloc (bad), and sizeof(n1) is always going to be 4 because it's a pointer. sizeof(char) is guaranteed to be 1 so you can omit that. You need to use strlen here:
    Code:
    p=malloc(strlen(n1)+1);
    You really don't need to be messing with dynamic allocation at all, the function can take the address of two arrays of whatever length you want (passed in from main) and create the reversed copy in the second.

    Code:
    for(i=strlen(n1)-1;i==0;i--)
    {
        p[i]=n1[i];
    }
    For any valid input, the i==0, part means this will always exit the loop without doing anything. Maybe you meant i>=0? You are also copying the data in directly without doing any reversal (and also forgetting the NULL in the reversed version).
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Code:
    //---------------------------------------------------------------------------
    
    #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    
    char *ReverseString(char *ptrString)
    {
    	if(ptrString == NULL)
    		return NULL;
    	else
    	{
    		char ptrChar;
    		int ptrIndex = 0;
    		int ptrLenght = strlen(ptrString);
    		for(; ptrIndex < ptrLenght; ptrIndex++)
    		{
    			ptrChar = ptrString[ptrIndex];
    			ptrString[ptrIndex] = ptrString[(strlen(ptrString)-1) - ptrIndex];
    			ptrString[(strlen(ptrString)-1) - ptrIndex] = ptrChar;
    			ptrLenght--;
    		}
    		return ptrString;
    	}
    }
    int main(int argc, char* argv[])
    {
    	char String[] = "yournamehere";
    	printf("&#37;s:%s\n",ReverseString("ReverseString"),ReverseString(String));
    	printf("Hit any key......\n");
    	getch();
    	return 0;
    }
    //---------------------------------------------------------------------------


    What to remember is that you need to exchange or swap the characters, so i can save the character to a character variable and then replace it with the last character of the input stirng and then the last character of the input string give the value of the char stored, having in mind to substract one from the length of the string so the loop to end in time.
    "I think you will better understand the code rather what i wrote"
    LOL.
    Last edited by Bokarinho; 09-20-2007 at 04:37 PM. Reason: Edit..Just.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Despite what Bokarinho says you can also do a reverse copy like you tried.

    To do the reverse copy you need two indices i and j:
    For any string length len, let j start at len - 1 counting down, and i starts at zero, counting up.
    Copy A[j] to B[i] while i < len.

    B is now the reverse of A.

  5. #5
    Sometimes so stupid... shardin's Avatar
    Join Date
    Jul 2007
    Location
    Dalmatia/CRO
    Posts
    78
    i get you citizen. it like this, i have this:

    Code:
    	for(i=strlen(n1)-1;i>=0;i--)// on 30 and every round -1,
    	{
    	for(j=0;j<strlen(n1)+1;i++)// but this one goes 1 2 3 4 5 6...
    	{
    		p[j]=n1[i];
    	}
    		
    	}
    but this j++, will continue to go up all the way, i need to tell him to stop after one round!
    ...and aprentice shall become master...or not...

    "Never let your sense of moral prevent you from doing what is right!" Salvor Hardin, mayor of Terminus

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    why do you use 2 loops when you need only one?

    the second index is easely calculated based on the index of the loop
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  7. #7
    Sometimes so stupid... shardin's Avatar
    Join Date
    Jul 2007
    Location
    Dalmatia/CRO
    Posts
    78
    this is the system:

    INDEX
    i -> j
    5->0
    4->1
    3->2
    2->3
    1->4
    0->5......
    ...and aprentice shall become master...or not...

    "Never let your sense of moral prevent you from doing what is right!" Salvor Hardin, mayor of Terminus

  8. #8
    Sometimes so stupid... shardin's Avatar
    Join Date
    Jul 2007
    Location
    Dalmatia/CRO
    Posts
    78
    Code:
    	for(i=0;i<strlen(n1)+1;i++)
    	{
    		j=strlen(n1)-1; // THIS GOES OUT!!!
    		p[j]=n1[i];
    		j--;
    		if(j==0)
    			break;
    	}
    something like this, output is messed up!! really im going crazy, this should work!!

    Correction: IM SO STUPID!!!!!

    it works, but still messed up like, zadar ->==radaz==2
    Last edited by shardin; 09-21-2007 at 05:40 AM.
    ...and aprentice shall become master...or not...

    "Never let your sense of moral prevent you from doing what is right!" Salvor Hardin, mayor of Terminus

  9. #9
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    You can get away with only looping halfway through the string. Something like this:
    Code:
    int end = strlen(str);
    int mid = end / 2;
    int i, temp;
    for(i=0; i<mid; i++)
    {
         temp = str[end-i];
         str[end-i] = str[i];
         str[i] = temp;
    }
    I havent tested it, but it should at least give you an idea.

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    *shrug* shardin, you're only problem is the indices again I think.
    All you need to do is walk backwards through a string.
    Code:
    #include <string.h>
    #include <stdio.h>
    
    char *reverse_copy( char dest[], const char src[] )
    {
      char *result = NULL;
      if( dest && src ) {
        size_t i, j;
        const size_t len = strlen( src );
        /**
        * For any string length len, let j start at len - 1 counting down,
        * and i starts at zero, counting up.
        * Copy A[j] to B[i] while i < len.
        **/
        for( i = 0, j = len - 1; i < len; i++, j-- ) {
          dest[i] = src[j];
        }
        /** B is now the reverse of A. **/
        dest[len] = '\0';
        result = dest;
      }
      return result;
    }
    
    int main( void )
    {
      char stra[] = "let's reverse a string";
      char strb[sizeof stra];
    
      if( reverse_copy( strb, stra ) ) {
        puts( stra );
        puts( strb );
      }
      return 0;
    }
    And mike_g is right too. You can reverse a string by walking through a string backwards and swapping elements with ones at the end.

  11. #11
    Sometimes so stupid... shardin's Avatar
    Join Date
    Jul 2007
    Location
    Dalmatia/CRO
    Posts
    78
    Works perfect now!! Thanks!
    ...and aprentice shall become master...or not...

    "Never let your sense of moral prevent you from doing what is right!" Salvor Hardin, mayor of Terminus

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stupid problem
    By Adrian20XX in forum C Programming
    Replies: 6
    Last Post: 08-23-2008, 08:16 AM
  2. Wrong Output
    By egomaster69 in forum C Programming
    Replies: 7
    Last Post: 01-28-2005, 06:44 PM
  3. Word COM problem
    By UnclePunker in forum Windows Programming
    Replies: 6
    Last Post: 01-06-2005, 11:51 AM
  4. A stupid chemistry problem
    By Shadow12345 in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 09-10-2002, 04:07 PM
  5. Using 'if' with char arrays or string objects
    By c++_n00b in forum C++ Programming
    Replies: 36
    Last Post: 06-06-2002, 09:04 PM