Saturday, December 24, 2011

Using just 1 line to copy a string

I dont know, where on this earth, that strcpy func is considered good..!!
when we can copy 1 string to another in just 1 line..

Below is a sample code(line) to copy the contents of string 's1' to string 's2':


yes,i m using a ';' jst after the while loop.
Actually,the fact is that a ';' jst after any loop is equivalent to '{ }', that is "empty curly braces".
So,the loop will run till the value at the address s1 is a NULL and copy the same character to the address contained in s2.
The post-increment operator first assigns the value at address contained in s1 to address contained in s2 and then increments the address stored in s1,pointing to the next character, till NULL is encountered.
Until a NULL is encountered, the assignment statement returns a non-zero value to the while and it runs.As the same is encountered,the condition returns a ZERO value to the while and the loop terminates.
but yes,the last assignment operation is done here,that's
when  *s1='\0' or *s1=0; (as you all know, ASCII value of '\0' is 0), it is assigned to the present address stored in s1;

Without this last assignment, s2 is not a complete string.In fact,it is not even a string, it's simply a character array.
Now, what's exactly the difference between both of them, that i'l xplain in some other post.

And u have to note 1 imp point here:
u can increment the base address of a string like this only in a function,not in main(think why??).
If u want to perform this operation in main,u have to use char pointers,pointing to both the strings, like:
char *s1="yash";
char *s2; 

hope this post is helpful :)


hostgator coupon 2012

No comments: