簡體   English   中英

strncpy轉換代碼中的等價性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM