pointer confusion

This is a discussion on pointer confusion within the C Programming forums, part of the General Programming Boards category; hi, What exactly happens in this program insert Code: void main() { char str1[]="Italy"; char str2[2]="Rome"; char *s1=str1,*s2=str2; while(*s1++ = ...

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    17

    pointer confusion

    hi,
    What exactly happens in this program
    insert
    Code:
    void main()
    {
      char str1[]="Italy";
      char str2[2]="Rome";
      char *s1=str1,*s2=str2;
      while(*s1++ = *s2++);
      printf("%s",str1);
    }
    according to me *s1++ = *s2++ will increment the pointer not the value pointed by it and then it stores the s2++ address inn to it.

    But i dont know how the while loop is ending...it is supposed to be an infinite loop since we are assigning s1 and s2 and not comparing any condition ????

    I am confused how the str1 points to rome at the end printf statement

    Please explain me what really happens at the back ???

    Regards,
    Ram

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    while(x = y) evaluates the same as while((x = y) != 0), and aside from x getting the value of y, it's the same as while(y != 0). The fact that you are using pointers and autoincrement doesn't change this basic principle.


    Code:
    char str2[2]="Rome";
    Rome is also longer than 2 characters - 5 is the correct number here.

    Also note that if you were to use, say, Napoli instead of Rome, you would have to specify a longer space for str1, as it is longer than "Italy".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting with pointer of pointers to array
    By dunpealslyr in forum C++ Programming
    Replies: 6
    Last Post: 10-01-2007, 11:26 PM
  2. (n00b) Pointer Confusion
    By kidburla in forum C Programming
    Replies: 5
    Last Post: 10-17-2005, 09:35 AM
  3. Question About Pointer To Pointer
    By BlitzPackage in forum C++ Programming
    Replies: 2
    Last Post: 09-19-2005, 10:19 PM
  4. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 01:19 AM
  5. Pointer confusion...
    By fkheng in forum C Programming
    Replies: 13
    Last Post: 06-23-2003, 10:18 PM

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