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




yogeshmk wrote:
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.
You didn't allocated memory for double pointer.
You are mallocing only for the strings.

This will solve the problem.
test_string = (char **) malloc (sizeof(char *) * n);

But it will lead to the issue of the size of row.

~yogesh

.



Relevant Pages

  • Re: Malloc code
    ... malloc() not return NULL? ... returned from malloc to an array of pointers, and then return this array of ... So I just returned a void pointer and assign the value to ... TCP_LOAD_MCB_X and I am assigning the values to the items of the strucutre ...
    (microsoft.public.vc.language)
  • 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: Can array[]=malloc()ed?
    ... > int main ... > in the above I have used array but derefered as a pointer since ... > first element in a array I wanted to malloc the array y. ...
    (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)