gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:54:40 26 4
gpt4 key购买 nike

我想了解如何在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com