0

I have a function

int executeCommand(char args[][TOKENSIZE]){
  char *argv[] = {args[0], args[1]}; // This works
  char *argv[] = {args}; // This doesn't
}

The args variable will not be of fixed length so I can't use the first line as it is. I don't want to use malloc or free due to some reasons. Is there any way of initializing this argv array from args without hard coding the number of entries.

7
  • 1
    Short answer: No. Long answer: Just pass the length of the args variable to the function so you know how many there are. Commented Sep 4, 2017 at 0:44
  • Even if there are how can I initialize it. Commented Sep 4, 2017 at 0:48
  • 2
    Why do you need to initialize it; it is a pointer. There's no need to copy the entire pointer array. Commented Sep 4, 2017 at 0:49
  • @chux args is not an array of pointers. Commented Apr 24, 2018 at 9:38
  • @MateoConLechuga the input is not a pointer array. Commented Apr 24, 2018 at 9:39

1 Answer 1

2

The function needs to know the size somehow or it is mission impossible. One possible way is to use pointers to VLA:

int executeCommand(size_t n, char args[n][TOKENSIZE]){
  char* argv[n];
  for(size_t i=0; i<n; i++)
  {
    argv[i] = args[i];
  }
}

As for you why you can't simply use args instead of copying the array addresses, I have no idea.

A complete hard-copy of the data would look like

char argv[n][TOKENSIZE];
memcpy(argv, args, sizeof(char[n][TOKENSIZE]));
Sign up to request clarification or add additional context in comments.

1 Comment

If argv[] is used like the argv[] of main(), then argv[n] should be NULL, so char* argv[n+1]; ... argv[n] = NULL;. BTW: Could use memcpy(argv, args, sizeof argv); Yet OP's goal is a bit unclear. Nice answer to old question.

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.