Func返回数组

时间:2012-12-15 18:44:15

标签: c++

请帮助我编写必须返回数组的函数这样的常见任务。我花了2个小时解决这个问题,但没有结果。这是我的代码:

 VERTEX* ConstructVertices(float R, unsigned int Slices)
{
    //const unsigned int n = static_cast<const unsigned int>(Slices);
    VERTEX *__vertices = new VERTEX[100];

    float dx = (2 * R) / Slices;
    float dz = dx;
    float x, y, z;
    x = -R;
    y = 0.5f;
    z = 0;
    int x_sign = 1;
    int z_sign = -1;

    __vertices[0].Color = D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f);
    __vertices[0].Pos = D3DXVECTOR3(x, y, z);

    for (int i=1; i<Slices * 4 + 1; i++)
    {
        __vertices[i].Color = D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f);

        y = -y;

        if (y < 0)
        {
            __vertices[i].Pos = D3DXVECTOR3(x, y, z);
            continue;
        }

        x += x_sign * dx;
        z += z_sign * dz;

        x = round_up(x, 2);
        z = round_up(z, 2);

        if (abs(x) == abs(R))
        {
            x_sign = -x_sign;
        }
        if (abs(z) == abs(R))
        {
            z_sign = -z_sign;
        }

        __vertices[i].Pos = D3DXVECTOR3(x, y, z);   
    }

    return __vertices;
}

访问阵列的代码:

VERTEX *vertices = new VERTEX[100];
vertices = ConstructVertices(1, 10);

使用Watches窗口,我可以看到顶点[0],顶点[1]等值。但是我不能将它看作一个数组&amp;主要是sizeof(vertices)返回4而不是160 !!

非常感谢!

4 个答案:

答案 0 :(得分:1)

只需返回std::vector<VERTEX>

返回指向堆上分配的内存的指针有几个主要问题:

  1. 如果没有妥善处理,内存很容易泄漏。
  2. 从界面上不清楚内存是如何发布的,编译器无法帮助使用正确的方法(尽管使用delete[] a;可能会猜测正确的方法是什么)。 / LI>
  3. 您无法从指针确定返回数组的大小。
  4. 显然,您可以创建一个提供合适操作的类,但这就是std::vector<T>。如果需要指向元素的指针,只需使用非空向量(&a[0])或a.data()的第一个元素的地址。后者是在C ++ 2011中引入的,并且具有使用空数组的优点(当然,返回的指针不能被解引用)。

答案 1 :(得分:1)

在您的代码中,您首先动态分配内存:

VERTEX *vertices = new VERTEX[100];
vertices = ConstructVertices(1, 10);

然后在函数中使用new分配内存:

//const unsigned int n = static_cast<const unsigned int>(Slices);
VERTEX *__vertices = new VERTEX[100];

最后返回此指针并替换您创建的第一个指针。内存分配两次。

答案 2 :(得分:0)

“主要是sizeof(顶点)返回4而不是160!”那是因为顶点是指针,显然你使用的是高科技的32位计算机,所以指针的大小是4个字节。
另一点是:

VERTEX *vertices = new VERTEX[100];
vertices = ConstructVertices(1, 10);

第一个任务没用,因为第二个任务被覆盖而没有使用,所以你只需用100 VERTEX泄漏内存。

答案 3 :(得分:0)

而不是这个

VERTEX *vertices = new VERTEX[100];
vertices = ConstructVertices(1, 10);

将顶点数组作为参数添加到函数中,并告诉函数大小

VERTEX *vertices = new VERTEX[100];
ConstructVertices(1, 10,vertices,100);

然后在你的函数内部填充传递的数组

void ConstructVertices(float R, 
                       unsigned int Slices,
                       VERTEX* vertices, 
                       size_t verticesArraySz )
{
    //const unsigned int n = static_cast<const unsigned int>(Slices);

    float dx = (2 * R) / Slices;
    float dz = dx;

...

不要使用__vertices之类的名称,这不是一个好习惯,因为通常编译器特定的东西使用该语法。