簡體   English   中英

C ++無符號字符數組

[英]C++ array of unsigned char arrays

我試圖了解如何在C ++中創建和處理無符號字符數組。 如:

Array[0] = { new array of unsigned chars }
Array[1] = { new array of unsigned chars }
Array[2] = { new array of unsigned chars }
....and so on

我已經編寫了下一個代碼,但是我感覺自己做錯了什么。 該代碼可以正常工作,但是我不知道聲明“緩沖區”的方式以及如何刪除緩存的方法是否正確,或者是否會產生內存泄漏。

#define MAX_BUFFER 10

unsigned char* cache[MAX_BUFFER];
bool cache_full = false;

void AddToCache(unsigned char *buffer, const size_t buffer_size)
{
    if (cache_full == true)
    {
        return;
    }

    for (int index = 0; index < MAX_BUFFER; index++)
    {
        if (cache[index] == NULL)
        {
            cache[index] = new unsigned char[buffer_size];
            memcpy(cache[index], buffer, buffer_size);
        }

        if (index < MAX_BUFFER - 1)
        {
            cache_full = true;
        }
    }
}

void ClearCache()
{
    for (int index = 0; index < MAX_BUFFER; index++)
    {
        if (cache[index] != NULL)
        {
            delete[] cache[index];
            cache[index] = NULL;
        }
    }

    cache_full = false;
}

bool IsCacheFull()
{
    return cache_full;
}

這樣行嗎

memcpy(cache, buffer, buffer_size);

不應該這樣 那會用buffer的內容覆蓋cache所有指針。 在上下文中,這可能應該是:

memcpy(cache[index], buffer, buffer_size);

另外,每次添加到緩存中時,都將重復將cache_full設置為true 嘗試:

AddToCache(unsigned char *buffer, const size_t buffer_size)  
{
  for (int index = 0; index < MAX_BUFFER; index++)
  {
    if (cache[index] == NULL)
    {
        cache[index] = new unsigned char[buffer_size];
        memcpy(cache[index], buffer, buffer_size);
        return(index);  // in case you want to find it again
    }
  }

  // if we get here, we didn't find an empty space
  cache_full = true;
  return -1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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