469,616 Members | 2,517 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,616 developers. It's quick & easy.

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?
Expand|Select|Wrap|Line Numbers
  1. int main() 
  2.         char *p1=“name”; 
  3.         char *p2; 
  4.         p2=(char*)malloc(20); 
  5.         memset (p2, 0, 20); 
  6.         while(*p2++ = *p1++); 
  7.         printf(“%s\n”,p2); 
  8.       return 0;
  9. }
Feb 28 '08 #1
2 1323
Ganon11
3,652 Expert 2GB
Because you are incrementing the pointer as you go, when you finish copying, your pointer looks like this:

Expand|Select|Wrap|Line Numbers
  1. p2 ----------------------
  2.                         V
  3. | n | a | m | e | \0 | some more memory |
It will point just after the string you've finished copying.
Feb 28 '08 #2
Because you are incrementing the pointer as you go, when you finish copying, your pointer looks like this:

Expand|Select|Wrap|Line Numbers
  1. p2 ----------------------
  2.                         V
  3. | 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.
Feb 28 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by RadiationX | last post: by
669 posts views Thread by Xah Lee | last post: by
5 posts views Thread by chandanlinster | last post: by
10 posts views Thread by preethamkumark | last post: by
reply views Thread by aled | last post: by
10 posts views Thread by DavidSeck.com | last post: by
reply views Thread by devrayhaan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.