如何处理指针来定义函数?定义返回数组的函数的问题



假设我需要一个函数来生成一个数组 r[3] = {x, y, z},其中 x[1000], y[1000], z[1000] 每个都是数组,有 1000 个双浮点。我做了一个函数,它通过解压缩内存位置来返回我们需要访问 x、y,z 的 r 表单的位置。我有这样的代码:

double cylinder(double radius, double height)
{
double x[1000], y[1000], z[1000];
double theta = 0, dtheta = M_PI / 500, dz = height / 1000;
z[0] = 0;
y[0] = 0;
x[0] = radius;
for (int i = 1; i < 1000; i++)
{
z[i] = z[i - 1] + dz;
theta = theta + dtheta;
x[i] = radius * cos(theta);
y[i] = radius * sin(theta);
}
double * r[3] = {x,y,z};
return **r;
}

现在如果我使用

data = cylinder(5, 10);
cout<<data<<endl;

它应该返回一个位置,但为什么它返回 5。我需要有"数据"的位置,从中我将得到另外 3 个内存位置,其中 3 个在每个位置上都有 1000 个点。 我将非常感谢得到解决方案。

这可以通过使用标准库std::vectorstd::tuple结合使用来轻松修复,这就像一个非常轻量级的固定长度数组:

#include <vector>
#include <tuple>
std::vector<std::tuple<double,double,double>> cylinder(double radius, double height)
{
std::vector<std::tuple<double,double,double>> result;
double theta = 0;
double dtheta = M_PI / 500;
double dz = height / 1000;
// No need for an array or back-references here
double x = radius;
double y = 0;
double z = 0;
// Add the 0th entry
result.push_back({ x, y, z });
for (int i = 1; i < 1000; i++)
{
z += dz;
theta = theta + dtheta;
x = radius * cos(theta);
y = radius * sin(theta);
// Add subsequent entries
result.push_back({ x, y, z });
}
return result;
}

现在使用容器解决内存管理问题。

如果xyz在语义上很重要,你甚至可能想用这些属性做一个小struct,而不是给它更多的上下文。

最新更新