Thursday, November 30, 2023

Difference of strcpy and stpcpy in c++

The main difference is the return value of stpcpy.

stpcpy returns the pointer to the terminating \0 character of the target string. This immediately makes clear the purpose of stpcpy and the rationale behind its existence: this function is intended to be used as an intelligent replacement to strcat function in situations when you need to concatenate multiple sub-strings into one string. 
strcat works pretty poorly in such application. The problem with strcat is that it rescans the destination string every time you add something to it, thus doing lots of unnecessary work and basically generating more heat than light. For example, the following code suffers from that problem


const char *part1, *part2, *part3, *part4;
... 
char buffer[size]; /* assume that `size` is calculated properly */ 

strcpy(buffer, part1); 
strcat(buffer, part2); 
strcat(buffer, part3); 
strcat(buffer, part4);

This code can be reimplemented in a much more reasonable way by using stpcpy stpcpy(stpcpy(stpcpy(stpcpy(buffer, part1), part2), part3), part4); 

And if you don't like chained calls, you can use an intermediate pointer to store the return value of intermediate stpcpy calls
 
char *end = buffer; 
end = stpcpy(end, part1); 
end = stpcpy(end, part2); 
end = stpcpy(end, part3); 
end = stpcpy(end, part4);


Of course it is worth mentioning that strcpy and strcat are standard functions, while stpcpy is not. Refrerence : SOF

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...