C++ 中 BYTE 数组的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2182784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:26:27  来源:igfitidea点击:

Length of a BYTE array in C++

c++

提问by Rakesh K

I have a program in C++ that has a BYTE array that stores some values. I need to find the length of that array i.e. number of bytes in that array. Please help me in this regard.

我有一个 C++ 程序,它有一个存储一些值的 BYTE 数组。我需要找到该数组的长度,即该数组中的字节数。请在这方面帮助我。

This is the code:

这是代码:

BYTE *res;
res = (BYTE *)realloc(res, (byte_len(res)+2));

byte_lenis a fictitious function that returns the length of the BYTE array and I would like to know how to implement it.

byte_len是一个虚构的函数,它返回 BYTE 数组的长度,我想知道如何实现它。

回答by Alok Singhal

Given your code:

鉴于您的代码:

BYTE *res;
res = (BYTE *)realloc(res, (byte_len(res)+2));

resis a pointer to type BYTE. The fact that it points to a contiguous sequence of nBYTES is due to the fact that you did so. The information about the length is not a part of the pointer. In other words, respoints to only one BYTE, and if you point it to the right location, where you have access to, you can use it to get BYTEvalues before or after it.

res是一个指向 type 的指针BYTE。它指向一个连续的nBYTES序列的事实是由于您这样做了。有关长度的信息不是指针的一部分。换句话说,res只指向一个BYTE,如果你把它指向正确的位置,你可以访问的地方,你可以用它来获取它BYTE之前或之后的值。

BYTE data[10];
BYTE *res = data[2];
/* Now you can access res[-2] to res[7] */

So, to answer your question: you definitely know how many BYTEs you allocated when you called malloc()or realloc(), so you should keep track of the number.

所以,回答你的问题:你肯定知道BYTE你在调用malloc()or时分配了多少s realloc(),所以你应该跟踪这个数字。

Finally, your use of realloc()is wrong, because if realloc()fails, you leak memory. The standard way to use realloc()is to use a temporary:

最后,你的使用realloc()是错误的,因为如果realloc()失败,你会泄漏内存。标准的使用方法realloc()是使用临时的:

BYTE *tmp;
tmp = (BYTE *)realloc(res, n*2);
if (tmp == NULL) {
    /* realloc failed, res is still valid */
} else {
    /* You can't use res now, but tmp is valid. Reassign */
    res = tmp;
}

回答by Sam Harwell

If the array is a fixed size array, such as:

如果数组是固定大小的数组,例如:

BYTE Data[200];

You can find the length (in elements) with the commonly used macro:

您可以使用常用的宏找到长度(以元素为单位):

#define ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0]))

However, in C++ I prefer to use the following where possible:

但是,在 C++ 中,我更喜欢在可能的情况下使用以下内容:

template<typename T, size_t N>
inline size_t array_length(T data[N])
{
    return N;
};

Because it prevents this from occurring:

因为它可以防止这种情况发生:

// array is now dynamically allocated
BYTE* data = new BYTE[200];
// oops! this is now 4 (or 8 on 64bit)!
size_t length = ARRAY_LENGTH(data);
// this on the other hand becomes a compile error
length = array_length(data);

If the array is nota fixed size array:

如果数组不是固定大小的数组:

In C++, raw pointers (like byte*) are not bounded. If you need the length, which you alwaysdo when working with arrays, you have to keep track of the length separately. Classes like std::vectorhelp with this because they store the length of the array along with the data.

在 C++ 中,原始指针(如byte*)不受限制。如果您需要长度(在处理数组时总是这样做),则必须单独跟踪长度。类喜欢这方面的std::vector帮助,因为它们将数组的长度与数据一起存储。

回答by Patrick

In the C way of doing things (which is also relevant to C++) you generally need to keep a record of how long your array is:

在 C 的做事方式(这也与 C++ 相关)中,您通常需要记录数组的长度:

BYTE *res;
int len = 100
res = (BYTE *)realloc(res, (byte_len(len)));
len += 2;
res = (BYTE *)realloc(res, (byte_len(len)));

An alternative in the C++ way of doing things s to use the std::vectorcontainer class; a vector has the ability to manage the length of the array by itself, and also deals with the issues of memory management..

在 C++ 处事方式中的另一种选择是使用std::vector容器类;一个vector有能力自己管理数组的长度,也处理内存管理的问题。。

EDIT: as others have pointed out the use of realloc here is incorrect as it will lead to memory leaks, this just deals with keeping track of the length. You should probably accept one of the other replies as the best answer

编辑:正如其他人指出在这里使用 realloc 是不正确的,因为它会导致内存泄漏,这只是处理跟踪长度。您可能应该接受其他回复之一作为最佳答案

回答by Omnifarious

Given the information you seem to have available, there is no way to do what you want. When you are working with arrays allocated on the heap, you need to save the size somewhere if you need to work with it again. Neither newnor mallocwill do this for you.

鉴于您似乎拥有可用的信息,没有办法做您想做的事。当您使用堆上分配的数组时,如果您需要再次使用它,则需要将大小保存在某处。既new不会也malloc不会为你做这件事。

Now, if you have the number of items in the array saved somewhere, you can do this to get the total size in characters, which is the unit that reallocworks with. The code would look like this:

现在,如果您将数组中的项目数保存在某处,您可以这样做以获得以字符为单位的总大小,这是使用的单位realloc。代码如下所示:

size_t array_memsize = elems_in_array * sizeof(BYTE);

If you are really working with C++ and not C I would strongly suggest that you use the vector template for this instead of going to mallocand realloc. The vector template is fast and not anywhere near as error prone as rolling your own memory management. In addition, it tracks the size for you.

如果您真的使用 C++ 而不是 CI,强烈建议您为此使用矢量模板,而不是使用mallocrealloc。矢量模板速度很快,而且不像滚动你自己的内存管理那样容易出错。此外,它会为您跟踪尺寸。

回答by Martin York

When you allocate the pointer initially you also need to keep track of the length:

当您最初分配指针时,您还需要跟踪长度:

size_t  bufSize  = 100;
BYTE*   buf      = malloc(sizeof(BYTE ) * bufSize);

When you re-allocate you should be carefull with the re-alloc:

当您重新分配时,您应该小心重新分配:

BYTE*   temp     = realloc(buf,sizeof(BYTE ) * (bufSize+2));
if (temp != NULL)
{
    bufSize  += 2;
    buf       = temp;
}

回答by tony.ganchev

If it is a local variable allocated on the stack you can calculate it like this:

如果它是分配在堆栈上的局部变量,您可以这样计算:

BYTE array[] = { 10, 20, 30, ... };
size_t lenght = sizeof(array) / sizeof(BYTE);

If you receive a pointer to the beginning of the array or you allocate it dynamically(on the heap), you need to keep the length as well as the pointer.

如果您收到指向数组开头的指针或动态分配它(在堆上),则需要保留长度和指针。

EDIT: I also advise you use STL vector for such needs because it already implements dynamic array semantics.

编辑:我还建议您使用 STL 向量来满足此类需求,因为它已经实现了动态数组语义。