471,863 Members | 1,107 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,863 software developers and data experts.

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 1400
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
NeoPa
reply views Thread by NeoPa | last post: by
aboka
reply views Thread by aboka | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.