While loop misbehaving (or misunderstanding)

This is a discussion on While loop misbehaving (or misunderstanding) within the C Programming forums, part of the General Programming Boards category; Hi, I'm reading an int into a string, character by character. By process of elimination the problem is with the ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    7

    While loop misbehaving (or misunderstanding)

    Hi,

    I'm reading an int into a string, character by character.

    By process of elimination the problem is with the while loop, but no with the contents of the while loop.

    That is removing the while loop and typing the contents 5 times the program works (but lacks the generality the while loop provides)

    I find it odd that including the while loop prevents ANY of my printf's from working. The idea is that the while stops once tPtr reaches the Null character.

    Any ideas?

    Code:
    #include <stdio.h>
    
    int main()
    {
    	char str[40];
    	char tmp[10], *tPtr;
    	int num[] = {1234, 5678, 8900, 1212};
    	char *ptr;
    	
    	printf("test1\n\r");
    
    	ptr = str;
    
    	sprintf(tmp, "%d,", num[0]);
    	
    	printf("tmp %s\n\n", tmp);
    
    	tPtr = tmp;
    
    	while(tPtr)
    	{	
    		*ptr++=*tPtr++;
    	}
    
    	*ptr ='\0';
    
    	printf("t1 %s", str);
    
    return 0;
    
    }
    Thanks

    Matt.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,175
    Code:
    	while(tPtr)
    	{	
    		*ptr++=*tPtr++;
    	}
    Don't confuse the nul-terminator for strings with the NULL macro. You're seeing of tptr is NULL instead of seeing if *tPtr is '\0' (the nul-terminator).

    What you really wanted was: while(*tPtr)
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Aug 2006
    Posts
    7
    excellent, thank-you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. nested loop, simple but i'm missing it
    By big_brother in forum C Programming
    Replies: 19
    Last Post: 10-23-2006, 11:21 PM
  2. Replies: 6
    Last Post: 10-23-2006, 08:22 PM
  3. loop in a linked linked lists
    By kris.c in forum C Programming
    Replies: 6
    Last Post: 08-26-2006, 01:38 PM
  4. while loop help
    By bliznags in forum C Programming
    Replies: 5
    Last Post: 03-20-2005, 12:30 AM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM

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