0

Why sometimes strcpy uses like strcpy(variable, "");

20th Nov 2020, 8:14 AM
Samia Haque
Samia Haque - avatar
4 Answers
+ 1
Alpha Caspian Sorry for a little misleading information, when you do strcpy like that, it doesn't reset the string entirely, just that start point, the same as str[0] = '\0';, because s is a pointer that points to &str[0] so it only modifies the first character to null (and also because null is one character). So if you string is "Hello" for example, 'H' there will be '\0' or null but the rest still exist. But when you try to print out the entire string AFTER that strcpy (e.g. printf %s or puts(s)), it will print nothing out, because it reads \0 at the starting point (different story if you print the characters one by one). So visually, yes it will empty the string, but in reality, it only empties the first character, printing the whole string will be empty, but printing the string by each of its characters may not be empty.
24th Nov 2020, 11:50 PM
LastSecond959
LastSecond959 - avatar
+ 2
To empty the string.
20th Nov 2020, 9:01 AM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
+ 1
For definition you can use char str[n] = {}; (n is just for example). But after that, when you want to reset the string (emptied), instead of doing loop of n iterations, you can just simply use strcpy like that to make the string empty or reset the string to null.
23rd Nov 2020, 9:19 AM
LastSecond959
LastSecond959 - avatar
+ 1
LastSecond959 Now I understand. Thanks a lot.
24th Nov 2020, 4:51 AM
Samia Haque
Samia Haque - avatar