无符号字符数组的 C++ 数组

标签 c++ 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;
}

关于无符号字符数组的 C++ 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651739/

相关文章:

c++ - 成员函数模板不在 clang 上编译,但在 GCC 上编译

c++ - 在 GCC/CLang 自动矢量化中强制对齐加载/存储的对齐属性

c++ - 在 C++ 中,取消引用和获取索引零做同样的事情吗?

python - 如何在numpy中按索引累积数组?

C++ 数组作为函数参数

c++ - 将 QString 转换为 QJsonArray

javascript - 为什么这个 JavaScript includes() 特性有意义?

c++ - 行尾字数统计 (C++)

c++ - Visual Studio 2010- fatal error LNK1120 : 1 unresolved externals; c++

c++ - 如何检查对象数组是否具有引用的对象