![](/img/trans.png)
[英]passing an argument ( a struct in an array of structs within a struct) to a function in C
[英]C: Pointer to an array of structs inside a struct within a function
我对C很陌生。我创建了一个结构和一个结构数组来存储数据,并将每个结构传递给我的函数:
int dosomething(struct s1 *struct1, struct s2 *struct2);
struct S1 {
int a;
int b;
int c;
};
struct S2 {
double x;
double y;
double z;
};
int main()
{
int n = 200;
struct S1 s1;
struct S2 *s2 = malloc(n * sizeof(struct S2));
dosomething(&s1, &s2[0])
return 0;
}
int dosomething(struct S1 *s1, struct S2 *s2)
{
s1->a = 1;
s1->b = 2;
s1->c = 3;
s2[0].x = 1.1;
s2[1].x = 1.123233;
...
return 1;
}
随着时间的流逝,这变得很烦人,所以我决定将它们放在一起。 现在我正在做这个
struct S1 {
int a;
int b;
int c;
struct S2 *s2;
};
struct S2 {
double x;
double y;
double z;
};
int main()
{
int n = 200;
struct S1 s1;
struct S2 *s2 = malloc(n * sizeof(struct S2));
s1.s2 = s2;
dosomething(&s1)
return 0;
}
int dosomething(struct S1 *s1)
{
s1->a = 1;
s1->b = 2;
s1->c = 3;
s1->s2[0].x = 1.1;
s1->s2[1].x = 1.123233;
...
// OR
struct S2 *s2 = s1->s2;
s2[0].x = 1.1;
s2[1].x = 1.123233;
...
}
现在,事情是:我读了很多关于结构,数组,结构数组等的指针,但是我仍然不确定,我在这里做的是否正确。 C:指针的指针数组结构(分配/释放的问题) , C指针,指向结构的数组 , 如何声明指针在C结构的数组 , 指向在功能结构的阵列 。 我的项目越来越大,我只是不想通过尝试使其变得更好而变得更糟。
我是否需要创建一个指向s2.s1 [x]的指针数组?
我是否需要告诉一个指针(结构S2 * s2 = s1-> s2)s2有多少元素?
有陷阱吗?
它没有错,这取决于它是否符合您的要求,并且从长远来看,它是一个不错的设计选择。
另外,您可能可以
s1.s2 = malloc(sizeof *s1.s2);
if (s1.s2 == NULL)
error_handler(); // do not use s1.s2 after this
dosomething(&s1);
将一个结构,指针或数组放置在另一个结构内被称为composition 。 如果S2
数组属于该数组,则应将其放置在S1
结构中。
例如,一个Point
是一对(x, y)
坐标,因此很明显它应该由两个int
组成,即:
void do_stuff(struct Point pt);
优于:
void do_stuff(int x, int y);
但是绝对不要仅仅因为您想保留一些输入而这样做。 如果S2
装入S1
内,则执行此操作。 如果程序中没有“没有S2
S1
”,那就有意义。
因此,如果这两个结构不属于一起,但是您发现自己将相同的参数序列传递给多个函数,则可以使用一种称为“引入参数对象”的OOP重构技术。 即而不是这样做:
do_stuff(&s1, &s2, &s3);
您可以创建一个新的结构,其结构仅由这些参数组成:
struct StuffParameters {
struct S1 * s1;
struct S2 * s2;
struct S3 * s3;
};
然后,您可以将其传递给多个“相似”功能:
struct StuffParameters parameters = { &s1, &s2, &s3 };
do_stuff(¶meters);
do_some_other_stuff(¶meters);
yet_another_function(¶meters);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.