c - 如何将结构体指针数组传递给函数?

标签 c pointers struct compound-literals

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

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}

因为它试图说初始化器 {.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)

关于c - 如何将结构体指针数组传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53158853/

相关文章:

c - 指针的奇怪行为

c - 将字符数组作为函数参数传递

c++ - 通过引用或指针返回并检查是否为空?

c++ - C++结构语法 "a : b"是什么意思

c - 如何确定确切原因,为什么 berkeley db 在 db->open 上返回 EINVAL?

Swift:间接访问/可变

c++ - 了解指向成员的指针运算符

typedef 的类型冲突

C++ 函数返回指向结构的指针变得奇怪

c - 生成随机数代码