C中的可变参数

#include <iostream>
#include <stdio.h>
#include <stdarg.h>

using namespace std;

int max(int n,...)
{
    va_list ap; 
    va_start(ap,n);
    int nMax = 0;
    int temp;
    for(int i=0;i<n;i++)
    {   
        temp = va_arg(ap,int);
        if(nMax < temp)
        {   
            nMax = temp;
        }   
    
    }   
    va_end(ap);
    return nMax;
}
char *display(const char *msg,...)
{
	if(!msg)
	{
		return NULL;
	}
	char *buf = new char[1024];
	memset(buf,0,sizeof(buf));
	va_list args;
	va_start(args,msg);
	vsprintf(buf,msg,args);
	va_end(args);
	
	return buf;
}
int main()
{

  	cout << max(4,2,90,15,100) << endl;
	cout << display("this is my ... test%d%s%d%s%d",520,"11111",1314,"11111",666) << endl;
	system("pause");
   return 0;
}     

猜你喜欢

转载自blog.csdn.net/qq_18286031/article/details/81117064