c++ - length of array inside class function [duplicate]

▼魔方 西西 提交于 2019-12-20 06:03:26

问题


i know there are several threads asking a similar question but i couldn't find a solution and i'm somewhat new to c++.

I want to calculate the length of a DWORD array. So it's just an unsigned long.

DWORD offsets[] = {0x378, 0x14, 0x0};

This is my header definition of the func:

DWORD allocateAddress(DWORD, DWORD[]);

This is inside the cpp function:

DWORD Window::allocateAddress(DWORD baseAddress, DWORD offsets[])
{
    DWORD buffer;
    DWORD pointer;

    int level = 3; // Length of offset array should be calculated here.

    for (int c = 0; c < level; c++)
    {
        if (c == 0)
        {
            buffer = this->read(baseAddress); 
        }

        pointer = buffer + offsets[c];
        buffer = this->read(pointer);
    }

    return pointer;
}

This is how i would calculate the length:

sizeof(offset) / sizeof(*offset) // or sizeof(offset[0])

If i do it like this inside the allocateAddress function, i only get 4 bytes. Testing it in the main method returns 12 bytes, which is the value i want.

std::cout << sizeof(Address::offset) << std::endl;

Why am i getting the size of a 1 dimensional DWORD? =(


回答1:


This is because C/C++ does not save the length of an array anywhere in memory.

The "offsets" parameter is declared as an array of undefined length. this is of course correct since you want to support any array, BUT this means that there is no way to know the size of the array at runtime.

Think of it this way: the "sizeof" keyword returns a result based on the declaration of the variable ONLY and not the actual size at runtime.

If your variable is delcared this way:

DWORD offsets[3]

Then its type is an "array of 3 DWORDs" (DWORD[3]), so sizeof will return the size in bytes of a "array of 3 DWORDs" or 12 bytes. In your case, the size of the array is implicitly defined as DWORD[3] because you initialize it with three values.

But if you declare a parameter as:

DWORD offsets[]

Its type becomes an "array of unknown length" (or DWORD[]). Since this is functionnaly identical to a constant pointer, "sizeof" will acts as if there is one element. So "sizeof" returns 1 * sizeof(DWORD) = 4.




回答2:


A template function can pass the size of a static array:

template <size_t COUNT>
DWORD allocateAddress(DWORD baseAddress, DWORD (&offsets)[COUNT]) {
    // now, sizeof(offsets) gives the expected size
    // as a bonus, you could also access the element count in COUNT
}

Usually, templates are inlined inside the Window class definition, in the header file (so I got rid of the Window:: scope specifier).



来源:https://stackoverflow.com/questions/16618221/c-length-of-array-inside-class-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!