What's Happening Here - Program Prints Empty Array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sarandnl08
    New Member
    • Feb 2008
    • 3

    What's Happening Here - Program Prints Empty Array?

    Hi all,

    I can't find any problem in this program, i getting empty string as output, why?
    what happening here any one help?
    [code=c]
    int main()
    {
    char *p1=“name”;
    char *p2;
    p2=(char*)mallo c(20);
    memset (p2, 0, 20);
    while(*p2++ = *p1++);
    printf(“%s\n”,p 2);
    return 0;
    }[/code]
    Last edited by sicarie; Feb 28 '08, 02:19 PM. Reason: Code tags are [code=c] and after your code [/code]. Please use them. They want to be used. They like to be used.
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Because you are incrementing the pointer as you go, when you finish copying, your pointer looks like this:

    Code:
    p2 ----------------------
                            V
    | n | a | m | e | \0 | some more memory |
    It will point just after the string you've finished copying.

    Comment

    • sarandnl08
      New Member
      • Feb 2008
      • 3

      #3
      Originally posted by Ganon11
      Because you are incrementing the pointer as you go, when you finish copying, your pointer looks like this:

      Code:
      p2 ----------------------
                              V
      | n | a | m | e | \0 | some more memory |
      It will point just after the string you've finished copying.

      Ya i understood, Thank you very much for your help.

      Comment

      Working...