0

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**

CodeSammich
  • 150
  • 1
  • 2
  • 10
  • Remember that `args` is a local variable and will be destroyed when you `return`. So you would end up returning a dangling pointer anyway. – Emil Laine Nov 24 '15 at 18:50
  • But if I try to malloc, I get a variable initializer error. What can I do? – CodeSammich Nov 24 '15 at 18:54
  • What is that? Can you paste the exact error message? – Emil Laine Nov 24 '15 at 18:55
  • parse.c:76:9: error: variable-sized object may not be initialized char *args[arg_num] = malloc( sizeof(char) * strlen(line)); //[ delim_count + 2 ]; //plus the last seat for NULL – CodeSammich Nov 24 '15 at 18:57
  • 1
    `malloc` returns a pointer to the allocated memory, but you're trying to use that to initialize an _array_. The two types are simply not compatible. – Emil Laine Nov 24 '15 at 19:00
  • If I change it back to a ** (with malloc), I get a bus error. – CodeSammich Nov 24 '15 at 19:11
  • 2
    First: Do you know what `char *a[b]` and `char **a` actually mean? – user253751 Nov 24 '15 at 19:12
  • char *a[b] is an array of char* (pointers) . The array is of length b. char **a is a pointer to a string? I'm not too sure. I get the impression that it's an array of strings, so idk – CodeSammich Nov 24 '15 at 21:42

2 Answers2

3

args is a local array on the stack. When the function returns it gets destroyed, so that you cannot return it from the function.

To survive the return from the function you need to allocate it on the heap. Instead of char *args[arg_num]; do char** args = malloc(sizeof *args * arg_num);.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
2

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157