c++ - length of array inside class function [dupli

2019-03-05 09:20发布

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? =(

2条回答
男人必须洒脱
2楼-- · 2019-03-05 09:26

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.

查看更多
别忘想泡老子
3楼-- · 2019-03-05 09:36

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).

查看更多
登录 后发表回答