【问题标题】:How to pass an array of pointer to structures to a function?如何将指向结构的指针数组传递给函数?
【发布时间】:2018-11-05 16:56:24
【问题描述】:

考虑一个表示笛卡尔坐标点的结构。

struct point { float x, y; };
typedef struct point point_t;

我有一个函数,它接收一堆点并根据传递的点绘制一条曲线,其定义如下所示,

void beziercurve(int smoothness, size_t n, point_t** points)

我已经编写了函数bezier,我想测试我的函数是否正常工作。因此,在主函数内部,我通过复合文字将以下虚拟值传递给函数,

point_t **p={(point_t*){.x=1.0, .y=1.0},
             (point_t*){.x=2.0, .y=2.0},
             (point_t*){.x=4.0, .y=4.0}};
beziercurve(100, 3, p);

LLVM 给我以下错误,

bezier.c:54:44: error: designator in initializer for scalar type 'point_t *'
  (aka 'struct point *')
    point_t** p=(point_t**){(point_t*){.x=1.0,.y=1.0},(point_t*){.x=2.0,.y=2.0...
                                       ^~~~~~

我什至尝试过这样的事情,

point_t **p={[0]=(point_t*){.x=1.0, .y=1.0},
             [1]=(point_t*){.x=2.0, .y=2.0},
             [2]=(point_t*){.x=4.0, .y=4.0}};
beziercurve(100, 3, p);

但这也行不通。我的逻辑是这样的:(point_t*){.x=1.0, .y=1.0} 创建一个指向临时结构的指针,然后在波浪形括号内的一堆结构指针创建一个我可以传递给函数的指针数组。

我错过了什么?为什么代码不起作用?

【问题讨论】:

  • (point_t*){.x=1.0, .y=1.0} 创建一个指向临时结构的指针 - 指针没有字段,因此您的语法根本无效。您可以创建 结构 本身的复合文字并传递它的地址,例如 &(point_t){.x=1.0, .y=1.0}
  • @EugeneSh。你能写下整个数组的初始化吗?对我来说,point_t** p={&(point_t){.x=1.0,.y=1.0},&(point_t){.x=2.0,.y=2.0},&(point_t){.x=4.0,.y=4.0}}; 可以通过警告编译,但会给我一个 SIGSEGV。

标签: c pointers struct compound-literals


【解决方案1】:

这个复合文字不起作用:

(point_t*){.x=1.0, .y=1.0}

因为它试图说初始化器 {.x=1.0, .y=1.0} 是一个指针,但它不是。

要创建指向结构的指针数组,您需要这样做:

point_t *p[]={&(point_t){.x=1.0, .y=1.0},
             &(point_t){.x=2.0, .y=2.0},
             &(point_t){.x=4.0, .y=4.0}};

但是,我怀疑您真正需要的只是一个结构数组。然后你可以像这样创建它:

point_t p[] = {
    {.x=1.0, .y=1.0},
    {.x=2.0, .y=2.0},
    {.x=4.0, .y=4.0}
};

然后您将更改您的函数以获取指向point_t 的指针:

void beziercurve(int smoothness, size_t n, point_t *points)

【讨论】:

  • 但是在void beziercurve(int, size_t, point_t*) 中,最后一个参数不是只接受一个指向一个结构的指针吗?
  • 是一个数组,所以point_t *points包含了数组的起始地址。可以像在数组中一样通过索引 [1] 访问连续的 point_t ,即
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 2018-04-15
  • 1970-01-01
  • 2021-11-02
  • 2019-05-03
相关资源
最近更新 更多