1

说,在我想从 file1.c 解析 C 结构的其他元素中:

typedef struct mynode{
   int* x;
   int length;
}node;

int callerFunction(int myLength){
  //memory space  
  node* n = (node*)malloc(sizeof(node));

  //dummy values for explanation purpose only
  double d = 3.14;
  int max  = 100;



//populate struct
  n->length = myLength;
  for(int i =0; i < n->length; i++)
     n->x[i]= i;

  //calling foo passing an structure  
   int result = foo(3,d,max,n);
}

我想通过 va_arg 将这个结构传递给另一个函数,在 file2.c

int foo(int n,...){

int foo_max;
double foo_d;
node* foo_n;
va_list ap;

va_start(ap,n);  
 d = va_arg(ap,double);
 foo_d = va_arg(ap,int);
 foo_n = va_arg(ap,node*);
va_end(ap);
....
}

我以为我在做正确的事情,但是如果我包含结构,则 foo 收集的数据是完全错误的(不是正确的数据)。我在这里做错了什么?

4

1 回答 1

2

内部callerFunction
似乎您没有分配内存n->x但正在使用它。

 //populate struct
 n->length = myLength;

 n->x = malloc(n->lenght * sizeof(int));     //////////add this line

 for(int i =0; i < n->length; i++)
     n->x[i]= i;
于 2012-06-21T18:25:54.767 回答