Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a function with a variable number of parameters?

How do I call execlp() with a variable number of arguments for different processes?

like image 708
Nullpoet Avatar asked Jan 21 '10 08:01

Nullpoet


2 Answers

If you don't know how many arguments you'll need at the time you are writing your code, you want to use execvp(), not execlp():

char **args = malloc((argcount + 1) * sizeof(char *));
args[0] = prog_name;
args[1] = arg1;
...
args[argcount] = NULL;

execvp(args[0], args);
like image 119
R Samuel Klatchko Avatar answered Oct 21 '22 11:10

R Samuel Klatchko


This answers only the title question

From Wikipedia Covers old and new styles

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

void printargs(int arg1, ...) /* print all int type args, finishing with -1 */
{
  va_list ap;
  int i;

  va_start(ap, arg1); 
  for (i = arg1; i != -1; i = va_arg(ap, int))
    printf("%d ", i);
  va_end(ap);
  putchar('\n');
}

int main(void)
{
   printargs(5, 2, 14, 84, 97, 15, 24, 48, -1);
   printargs(84, 51, -1);
   printargs(-1);
   printargs(1, -1);
   return 0;
}
like image 29
stacker Avatar answered Oct 21 '22 11:10

stacker