strcpy和“=”之间有什么区别?

我想知道char* test = "test"strcpy(test, "test")是否有区别,如果有的话,这是什么区别。

谢谢。

strcpy函数( 你不应该使用它! – 使用strncpy或strdup来避免缓冲区溢出漏洞),将字节从一个字符串缓冲区复制到另一个字符串缓冲区; 赋值更改您指向的缓冲区。 请注意,要调用strncpy(或strcpy,但不要!),您需要已经分配了一个缓冲区来执行此复制。 当您从文字字符串进行赋值时,编译器已经有效地创建了一个只读缓冲区,并使用该地址更新指针。

UPDATE

正如评论中所指出的,strncpy也有其缺点。 最好使用自己的辅助函数将数据从一个缓冲区复制到另一个缓冲区。 例如:

 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; } 

并且,如果您可以使用C ++,而不仅仅是C,那么我建议使用std::string