1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Of course, but you are only allowed to accept an answer after 10 minutes :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.