[英]how to pass struct pointer as argument in a variable argument function in C
I need to pass a struct pointer in my function which takes variable arguments.我需要在我的函数中传递一个带有可变参数的结构指针。 What is the correct way to do that.
这样做的正确方法是什么。 I tried this following code.Just pasting the code snippet, and not the full code.
我尝试了以下代码。只是粘贴代码片段,而不是完整代码。
struct node {
int label,
bool visited} vertex;
//My arguments in this function should be variable/unknown at runtime. It should take n number of streuct pointer arguments
int and_gate(struct vertex * v1, )
{
va_list valist;
va_start(valist, num) //not sure
int out=0;
for(int i=0;i<num,i++)
out = va_args(valist, v1);
}
int main()
{
struct vertex a,b,c;
and_gate(3, &a,&b,&c)
}
Use dynamic array使用动态数组
int and_gate(int n, struct vertex *v1)
{
for(int i = 0; i < n; ++i)
printf("%d", v1[0].label);
}
int main()
{
int n=3;
struct vertex *a;
a = malloc(n * sizeof(struct vertex));
and_gate(n, a);
}
First of all, there is no declaration of struct vertex
in your code.首先,您的代码中没有
struct vertex
声明。 This:这个:
struct node {
int label,
bool visited} vertex;
is just a definition of global variable named vertex
, that has type struct node
.只是一个名为
vertex
的全局变量的定义,它的类型是struct node
。 Declaration of required type looks next:接下来是所需类型的声明:
struct vertex {
int label,
bool visited
};
Then and_gate()
must be declared properly.然后
and_gate()
必须正确声明。 According to way how you use it, it probably should look like this:根据您使用它的方式,它可能应该是这样的:
int and_gate(int vert_num, ...)
{
va_list valist;
va_start(valist, vert_num);
struct vertex *vert;
for(int i=0; i < vert_num; i++) {
vert = va_arg(valist, struct vertex *);
/* do what you want with `vert` */
}
}
But anyway - using of stdargs here smells like overdesigned solution.但无论如何 - 在这里使用 stdargs 闻起来像是过度设计的解决方案。 Since passed data are homogeneous - it is better and more clear to pass array of
struct vertex
.由于传递的数据是同质的 - 传递
struct vertex
数组更好更清晰。 It may be both static or dynamic array, depending on context.它可以是静态或动态数组,具体取决于上下文。 Eg:
例如:
int and_gate(struct vertex * data, int num)
{
struct vertex *vert;
for(int i=0; i < num; i++) {
vert = data[i];
/* do what you want with `vert` */
}
}
int main()
{
struct vertex data[3] = { /* init array members */ };
and_gate(data, 3)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.