gpt4 book ai didi

c++ - 函数返回数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:52:46 25 4
gpt4 key购买 nike

请帮助我完成诸如编写必须返回数组的函数之类的常见任务。我花了 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 窗口中,我可以看到像 vertices[0]、vertices[1].. 这样的值,但我看不到它是一个数组,主要是 sizeof(vertices) 返回 4 而不是 160!!

非常感谢!

最佳答案

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

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

然后在函数中用新的分配内存:

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

最后你返回这个指针并替换你创建的第一个指针。内存被分配了两次。

关于c++ - 函数返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com