Search code examples
carraysshelldynamic-memory-allocation

How to make an argument array of strings in c


I have an array x of floating point numbers (of variable length n) which I want to pass to a shell script as command line arguments using execl(). I suppose I need to declare a pointer to a char array **args[] and then dynamically allocate this to have the length n and then do something like this:

 *args=malloc(n*sizeof(char[]);
    for(i=0;i<n;i++) sprintf( args[i] , "%f", x[i]);  
    execl("script.sh","script.sh", args, NULL);

However, I cannot get the allocation of args to work right. Could someone please hint at how this is done correctly?


Solution

  • You need to allocate room for both the array of character pointers, which is what you're going to pass to execv(), and the characters themselves. Note that you can't use execl() for this, you need to use the array-based ones, such as execv().

    char ** build_argv(const char *cmd, const float *x, size_t num)
    {
      char **args, *put;
      size_t i;
    
      /* Allow at most 64 chars per argument. */
      args = malloc((2 + num) * sizeof *args + num * 64);
      args[0] = cmd;
      put = args + num; /* Initialize to first character after array. */
      for(i = 0; i < num; ++i)
      {
        args[1 + i] = put;
        put += snprintf(put, "%f", x[i]);
      }
      args[1 + num] = NULL; /* Terminate array. */
      return args;
    }
    

    The above should work, it builds a NULL-terminated array of strings. You can free the entire array (and the strings) with a single free() call.