[英]strncpy To strcpy Equivilence in Code
我有這個丑陋的功能,我覺得整個strncpy
應該只是一個strcpy
:
void PackData(char*& cursor, const std::string& data) {
*(reinterpret_cast<int*>(cursor)) = static_cast<short>(data.length() + 1);
cursor += sizeof(int);
// copy the text to the buffer
::strncpy(cursor, data.c_str(), data.size());
cursor += (data.length() * sizeof(char));
*(reinterpret_cast<char*>(cursor)) = 0;
cursor += sizeof(char);
}
cursor
保證有足夠的空間來容納所有復制的數據。 並且data
在終止處僅包含'\\0'
字符。
我想更新此函數以使用strcpy
,並刪除一些難看的東西。 這是我所擁有的:
void PackData(char*& cursor, const std::string& data) {
const int size = data.size() + 1;
std::copy_n(cursor, sizeof(int), reinterpret_cast<char*>(&size));
cursor += sizeof(int);
strcpy(cursor, data.c_str());
cursor += size;
}
我的代碼工作正常,但是我想問問是否有人看到我可能錯過的任何不良行為?
編寫該代碼的人都不知道他們在做什么。 使用strncpy
沒有意義,因為在調用中傳遞給它的長度是源的長度,而不是目標的長度。 最后的reinterpret_cast
只是將cursor
轉換為其原始類型。 擺脫這種廢話。 您的代碼是很好的替代品。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.