C ++ - 长数组类函数内 [英] c++ - length of array inside class function

查看:135
本文介绍了C ++ - 长数组类函数内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有几个线程问过类似的问题,但我无法找到一个解决方案,我有点新的C ++。

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

我要计算一个DWORD阵列的长度。所以它只是一个unsigned long。

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

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

这是FUNC我的头定义:

This is my header definition of the func:

DWORD allocateAddress(DWORD, DWORD[]);

这是CPP函数中:

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

如果我不喜欢这样的allocateAddress函数里,我只得到4个字节。在main方法测试其返回12个字节,这是我想要的值。

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;

为什么我得到一个一维DWORD的大小? =(

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

推荐答案

这是因为C / C ++没有任何地方保存数组的长度在内存中。

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.

考虑一下这种方式:在sizeof的关键词返回一个基于变量的声明结果仅的,而不是在运行时的实际尺寸

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.

如果您的变量delcared是这样的:

If your variable is delcared this way:

DWORD offsets[3]

那么它的类型是( DWORD [3] ),这样的sizeof将在3个DWORDs阵的字节返回尺寸的3个DWORDs阵或12个字节。在你的情况下,数组的大小被隐式定义为 DWORD [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[]

它的类型变为未知长度的阵列(或 DWORD [] )。由于这是functionnaly相同恒定指针,sizeof的将充当如果有一个元素。因此,sizeof的返回1 *的sizeof(DWORD)= 4。

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.

这篇关于C ++ - 长数组类函数内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆