我正在努力了解如何创建&在C ++中处理一个unsigned char数组。如:
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;
}
答案 0 :(得分:0)
这有效吗?
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;
}
。尝试:
{{1}}