问题
I would like to know if there is a difference between char* test = "test"
and strcpy(test, "test")
, and if there is one, what is this difference.
Thanks.
回答1:
The strcpy function (which you should never use! -- use strncpy or strdup to avoid buffer overflow vulnerabilities), copies the bytes from one string buffer to the other; assignment changes the buffer to which you are pointing. Note that to invoke strncpy (or strcpy, but don't!) you need to have a buffer already allocated to do this copy. When you do an assignment from a literal string, the compiler has effectively created a read-only buffer, and your pointer is updated with the address of that.
UPDATE
As pointed out in the comments, strncpy has its drawbacks, too. You are much better off using your own helper functions to copy the data from one buffer to another. For example:
ReturnCode CopyString(char* src, char* out, int outlen) {
if (!src) {
return NULL_INPUT;
}
if (!out) {
return NULL_OUTPUT;
}
int out_index = 0;
while ((*src != '\0') && (out_index < outlen - 1)) {
out[out_index++] = *src;
src++;
}
out[out_index] = '\0';
if (*src != '\0') {
if (outlen > 0) {
out[0] = '\0'; // on failure, copy empty rather than partially
}
return BUFFER_EXCEEDED;
}
return COPY_SUCCESSFUL;
}
And, if you can use C++, not just C, then I would suggest using std::string
.
来源:https://stackoverflow.com/questions/41084469/what-is-the-difference-between-strcpy-and