top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to pass variable number of arguments in a C function?

+3 votes
377 views

Can someone help me with step by step example and may be with sample code.

posted Dec 24, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Use the <stdarg.h> header (or, if you must, the older <varargs.h>).

Here is a function which concatenates an arbitrary number of strings into malloc'ed memory:

#include <stdlib.h>     /* for malloc, NULL, size_t */
#include <stdarg.h>     /* for va_ stuff */
#include <string.h>     /* for strcat et al */

char *vstrcat(char *first, ...)
{
    size_t len = 0;
    char *retbuf;
    va_list argp;
    char *p;

    if(first == NULL)
        return NULL;

    len = strlen(first);

    va_start(argp, first);

    while((p = va_arg(argp, char *)) != NULL)
        len += strlen(p);

    va_end(argp);

    retbuf = malloc(len + 1);   /* +1 for trailing \0 */

    if(retbuf == NULL)
        return NULL;        /* error */

    (void)strcpy(retbuf, first);

    va_start(argp, first);

    while((p = va_arg(argp, char *)) != NULL)
        (void)strcat(retbuf, p);

    va_end(argp);

    return retbuf;
}

Usage is something like

char *str = vstrcat("Hello, ", "world!", (char *)NULL);
answer Dec 29, 2014 by Prakash
–1 vote

For this we need to use elipsis(...), and out job is doe, a sample could be like this
int function(int, ... )
{
/*Your code
*/
}

int main()
{
function(1, 2, 3);
function(1, 2, 3, 4);
}

answer Dec 27, 2014 by Atiqur Rahman
Similar Questions
+6 votes
+1 vote

Is it possible to pass command line arguments to C programs? If yes, can you write down the prototype for main function with command line arguments?

+2 votes

Is there a way to count the number of variadic macro arguments in C?

I found a way to check if the list is empty: examine sizeof(STR((__VA_ARGS__))) where STR is a macro that stringifies its argument. If it is 3, __VA_ARGS__ is empty. I wonder if there is a less hackish approach.

The macro arguments are expressions, but not of a uniform type, so an array-based approach does not work.

...