为什么va_arg在char*类型的变量参数列表的末尾返回NULL?

Rüp*_*ure 4 c variadic-functions null-pointer

这就是va_arg以下知名链接中所说的内容:

http://www.cplusplus.com/reference/cstdarg/va_arg/

Notice also that va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list). The function should be designed in such a way that the number of parameters can be inferred in some way by the values of either the named parameters or the additional arguments already read.

除此之外,在我读过的那本书中va_arg,所有的例子都确保其中一个fixed参数始终是我们要传递的变量参数的数量/数量.这个计数用在一个循环中进入va_arg下一个项目,并且循环条件(使用计数)确保它在va_arg检索变量列表中的最后一个参数时退出.这似乎证实了上述段落的说明"the function should be designed in such a way........" (above).

所以直言不讳,va_arg有点愚蠢.但是在下面的例子中,从该网站中获取va_end,va_arg突然似乎巧妙地行动.当char*到达类型的变量参数列表的末尾时,它返回一个NULL指针.怎么回事?我联系的最重要段落明确指出

"va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list"

并且,以下程序中没有任何内容确保在交叉变量参数列表的末尾时应va_arg返回NULL指针.那么如何在列表末尾返回NULL指针?

/* va_end example */
#include <stdio.h>      /* puts */
#include <stdarg.h>     /* va_list, va_start, va_arg, va_end */

void PrintLines (char* first, ...)
{
  char* str;
  va_list vl;

  str=first;

  va_start(vl,first);

  do {
    puts(str);
    str=va_arg(vl,char*);
  } while (str!=NULL);

  va_end(vl);
}

int main ()
{
  PrintLines ("First","Second","Third","Fourth",NULL);
  return 0;
}    
Run Code Online (Sandbox Code Playgroud)

产量

First

Second

Third

Fourth
Run Code Online (Sandbox Code Playgroud)

节目源链接

小智 11

char *到达类型的变量参数列表的末尾时,它返回一个NULL指针.怎么回事?

因为传递给函数的最后一个参数确实是NULL:

PrintLines("First", "Second", "Third", "Fourth", NULL);
Run Code Online (Sandbox Code Playgroud)