-1
我想將RingBuffer複製到LinearBuffer中。讓我們假設RingBuffer我們面對的是一個類型的RingBuff_t BUF,其中:將RingBuffer的內容移動到LinearBuffer
typedef struct
{
RingBuff_Data_t Buffer[BUFFER_SIZE]; /**< Internal ring buffer data, referenced by the buffer pointers. */
RingBuff_Data_t* In; /**< Current storage location in the circular buffer */
RingBuff_Data_t* Out; /**< Current retrieval location in the circular buffer */
RingBuff_Count_t Count;
} RingBuff_t;
看起來,我們需要把它devide爲兩種情況: 出現了「」是經過「輸出」指針或之前的時間。所以,我心中已經寫了這個代碼,但我不知道這是相當不錯的:
memset(linearBuffer,0,LINEAR_BUFFER_SIZE);
RingBuff_Data_t* tempIn = buf.In;
if (buf.Out < tempIn){
memcpy(linearBuffer,buf.Out,tempIn-buf.Out);
}
else if (buf.Out > tempIn){
strcpy(linearBuffer,buf.Out);
strncpy(linearBuffer+strlen(buf.Out),buf.Buffer,buf.In-buf.Buffer);
}
對不起,但RingBuffer和LinearBuffer的內容只是char類型的內容。 – Kobi
所以在這種情況下,我想沒有必要使用(sizeof)函數...我是對的嗎? 另外,爲什麼我需要在整個過程中使用memcpy?使用memcy和strcpy有什麼問題? – Kobi
'sizeof(char)== 1',所以沒有必要。 (但是,爲環形緩衝區數據定義特殊類型也是不必要的。)'strcpy'需要具有空終止的連續字符。我懷疑你的環形緩衝區數據是空的終止。你可以使用'strncpy',但使用你的參數,它和'memcpy'一樣。在你的情況下,你並沒有真的複製字符串,你正在複製充滿字符的內存範圍。 'memcpy'就是這個功能。 –