【问题标题】:Passing a mixed-type parameters to a function as a pointer, I think我认为将混合类型参数作为指针传递给函数
【发布时间】:2012-06-17 20:13:21
【问题描述】:

这是我第一次在这里发帖。请原谅我的经验不足;我只是在学习。

我正在尝试实现 GSL 寻根方法,它需要将因变量和参数结构传递给函数。

这是传递给函数的参数结构(在 .h 文件中):

struct SumForces_params
{
double curvature;
struct panel panels[1000];
int lenPanels;
};

这里是我定义参数实例的地方:

struct SumForces_params params = {0.0000001, {panels[1000]}, lenPanels};

函数如下:

double SumForces(double NAloc, void *params)
{
struct SumForces_params *p = (struct SumForces_params *) params;
double curvature = p->curvature; //works fine
int lenPanels = p->lenPanels; //works fine

struct panel panels = p->panels[1000];
//~ printf("panel 421 location = %g\n", panels[421].Yloc); 
//~ Above line gives this error: SumForces.c:54: error: subscripted value is neither
//~ array nor pointer

double yloc = 0;
yloc = p->panels[421].Yloc;
printf("panel 421 location = %g\n", yloc);
}

总的来说,这给了我预期的输出:

printf("Main Panel 421 loc = %g\n",panels[421].Yloc);

但是从函数代码中可以看出,struct panel panel = p->panels[1000];不起作用,第二次尝试(最后三行)的输出返回零。有人看到我做错了吗?

这是我对结构面板的定义:

struct panel
{
   double strain[136];
   double stress[136];
   double AE[136];
   double Ys;
   double E;
   double Yloc;
   double Area;
   gsl_interp_accel *acc_stress;
   gsl_spline *spline_stress;
   gsl_interp_accel *acc_AE;
   gsl_spline *spline_AE;
};

在这里,我将面板定义为 1000 个面板结构的数组:

struct panel panels[1000];

【问题讨论】:

    标签: c function pointers struct


    【解决方案1】:
    struct panel panels = p->panels[1000];
    

    p->panel1000 元素的数组。最后一个元素的索引为999,因为您从0 开始索引。所以,这个特定的行调用了 UB。你可能想要:

    struct panel panels = p->panels[ 999 ];
    

    【讨论】:

    • 德克,谢谢。这减轻了错误,但如果我随后打印 panel[999].Yloc,我仍然得到零。这让我相信我在定义参数结构的地方 struct SumForces_params params = {0.0000001, {panels[1000]}, lenPanels};是不正确的。面板已经定义;我在这里重新定义它吗?谢谢!
    • 您对params 的初始化不正确。这需要修复。第二个元素需要1000 类型的panel 对象数组,而您只传递一个(这也是越界访问)元素。很遗憾,我没有 struct panel 的定义来帮助您。
    • Dirk,我编辑了我的原始帖子以显示我对结构面板的定义以及我在哪里初始化了一个面板结构数组。谢谢!
    • @Matt:panels 对象需要适当的初始化函数(因为有指针、成员数组等)。
    【解决方案2】:

    编译器可能以错误的方式理解了您的语法(不是您所期望的),并且没有对此发出警告:

    struct SumForces_params params = {0.0000001, {panels[1000]}, lenPanels};
    

    我从您的问题中猜想您想将有关面板的数据复制到params。正确的做法是这样的:

        struct SumForces_params params =
        {
            0.0000001,
            {}, // C doesn't have syntax for "put panels here"
            lenPanels
        };
        memcpy(params.panels, panels, sizeof(params.panels));
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 2019-08-17
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多