我试图了解如何在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);

不应该这样这将用cache的内容覆盖buffer中的所有指针。在上下文中,这可能应该是:
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;
}

10-08 11:39