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

时间:2013-05-07 17:24:28

标签: c null-pointer variadic-functions

以下是有关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"

并且,以下程序中没有任何内容确保在交叉变量参数列表的末尾时应返回NULL指针。那么va_arg如何在此处返回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;
}    

输出

First

Second

Third

Fourth

Program Source Link

1 个答案:

答案 0 :(得分:10)

  

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

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

PrintLines("First", "Second", "Third", "Fourth", NULL);