char *arr[n] Vs. char **arr



I need to break a longer string (with strtok()) and store the smaller
strings in an array. since the number of small strings is not
fixed/known, I cannot use a declaration like char *format[n], so I
declared char** format = NULL;

Now the problem starts. Each time strtok() returns me a token (which is
char*), I call malloc() and I (want to) store the address returned in
the array format[], and copy the token to that address.

code snippet:
------------------
char **format = NULL;
char delim[] = ".-/:";
int i=0;

if ((tok = strtok(argv[1], delim)) != NULL)
{
if((format[i]=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}

for (i=1; tok; i++)
{
if ((tok = strtok(NULL, delim)) != NULL)
if((format[i]=(char*)malloc(strlen(tok))) != NULL)
strcpy(format+i, tok);
}

The malloc statement gives a segfault. In desparation, I have tried
various combinations of lvalue in malloc, but none of them were correct
(either I get a compiler warning like "invalid lvalue", or "assignment
makes an integer from pointer" etc.. or if compilation is successful,
run always fails with a segfault)

Q: Is above approach fundamentally incorrect? Can I declare something
as a pointer to pointer to char & treat like an array of strings? If
yes, what's wrong in above code? I have no hesitation in admitting that
my pointer fundamentals are not very clear yet -:)
~yogesh

.



Relevant Pages

  • Re: two dimensional arrays passed to functions
    ... > array and then send it down as a single dimmensional array. ... x is an array of char pointers. ... to a pointer to the first element of this array, ... need to copy the strings and not just assign pointers to them). ...
    (comp.lang.c)
  • Re: low-level pointer vs. array question
    ... that the array version is indeed superiour for my purposes. ... memory for pointer variables. ... Note that "it allocates memory only for the strings" ...
    (comp.lang.c)
  • Re: fast stable sort
    ... rather than isolating it in a separate array. ... It lumps an extra pointer in with the only one ... Building a linked list does not constitute using Oextra space. ... strings and linking the strings into an order. ...
    (comp.programming)
  • Re: char *arr[n] Vs. char **arr
    ... since the number of small strings is not ... the array format[], and copy the token to that address. ... The malloc statement gives a segfault. ... makes an integer from pointer" etc.. ...
    (comp.lang.c)
  • Re: char *arr[n] Vs. char **arr
    ... since the number of small strings is not ... the array format[], and copy the token to that address. ... The malloc statement gives a segfault. ... makes an integer from pointer" etc.. ...
    (comp.lang.c)