简体   繁体   English

不允许使用 va_list 变量的地址? 错误:从不兼容的指针类型赋值?

[英]address of a va_list variable is not allowed? Error: assignment from incompatible pointer type?

Code to duplicate this on Linux is as follows:在 Linux 上复制它的代码如下:

GCC 4.8.5 20150623 (Red Hat 4.8.5-44) No i can't change this, it's on CentOS7 and its a requirement to stay there) GCC 4.8.5 20150623 (Red Hat 4.8.5-44) 不,我不能改变这个,它在 CentOS7 上,它需要留在那里)

#include <stdarg.h>

struct foo {
  va_list *pAP;
  const char *fmt;
};

void format_output( struct foo *pFoo );

void my_vprintf( const char *fmt, va_list ap )
{
  struct foo x;

  x.fmt = fmt;
  // why is this not allowed?
  x.pAP = &ap; // <- ERROR/WARNING: assignment from incompatible pointer type

  format_output( &x );
}

void my_printf( const char *fmt, ... )
{
  va_list ap;

  va_start( ap, fmt );
  my_vprintf( fmt, ap );
}

It's not allowed because on your implementation, va_list happens to be an array type.这是不允许的,因为在您的实现中, va_list恰好是数组类型。 That's allowed by the standard, but not required.这是标准允许的,但不是必需的。 (And it's a bit annoying.) (这有点烦人。)

When you use an array type as a function parameter, it "decays" to a pointer type (a pointer to the first element in the array), which is not compatible with a pointer to the array type (which is what the pAP member of struct foo is).当您将数组类型用作 function 参数时,它“衰减”为指针类型(指向数组中第一个元素的指针),这与指向数组类型的指针(这是pAP成员struct foo是)。

A simple workaround is to create the struct foo in my_printf rather than creating it in my_vprintf .一个简单的解决方法是在my_printf中创建struct foo而不是在my_vprintf中创建它。 Another possibility is to make the struct foo member a va_list rather than a pointer to a va_list , and use va_copy rather than assignment.另一种可能性是使struct foo成员成为va_list而不是指向va_list的指针,并使用va_copy而不是赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM