Search code examples
carrayspointersdouble-pointer

How to convert char *a[] into char **?


I'm trying to return a char** while working with an array of char*

Is there any way I could do this effectively?

  char *pos;
  if ((pos=strchr(line, '\n')) != 0) 
     *pos = '\0';

  //parses command in input (max of (arg_num - 2) flags)
  int arg_num = count_tokens( line, delim);

  char *args[arg_num]; // = malloc( sizeof(char) * strlen(line)); //[     delim_count + 2 ];  //plus the last seat for NULL

  //puts cmd && flags in args
  int i = 0;
  for(; i < arg_num; i++) 
    //strcpy(args[i], strsep( &line, " "));
    args[i] = strsep( &line, " ");

  char** a = args;
  return a;

EDIT: If I'm using char**, how can I get it to work like an array, in terms of setting and accessing the strings (with strsep). I'm kind of confused on the whole concept of a char**


Solution

  • args is a local variable and will be destroyed when you return, so you clearly cannot return a pointer to it. You have to think of something else.

    You could allocate args dynamically:

    char **args = malloc(sizeof(*args) * arg_num);
    

    Then args is of the right type to begin with.