1

I used strtok to split a string.

[UPDATE] I used your comments and answer for the new version below, but didn't work atm

int Crawl :: splitUrl(char ***tmp, int max_length, char *url)
{
 int idx=0;
 char * p;
 int i;

 p = strtok (url,"/");
 while (p != NULL && idx < max_length)
  {

   for (i=0;i<maxUrlSize-1 && p[i] != '\0';i++)
    (*tmp)[idx][i] = p[i];
   for ( ; i< maxUrlSize-1;i++)
    (*tmp)[idx][i] = '\0';

   printf("tmp[idx[%d]] %s\n",idx,(*tmp)[idx]);

   idx++;
   p = strtok (NULL, "/");
  }

 return idx;
};

The printf("tmp[idx] ... is correctly printed.

But in my main after I run the method:

  split_url = new char * [ maxUrlSplits ];
  for (int k=0;k<maxUrlSplits;k++)
   split_url[k] = new char [maxUrlSize];

  arr_size = crawl->splitUrl(&split_url,maxUrlSplits,url);

the array split_url is empty.

Compiler and gdb are fine.

Does someone have an idea?

Xyz
  • 5,955
  • 5
  • 40
  • 58
Roby
  • 2,011
  • 4
  • 28
  • 55
  • how do you know the array is empty? I can run it without any problem. The array split_url is not empty. – Eric Z May 01 '11 at 08:42
  • A bit OT but this is obviously C++, so why use arrays in the first place? – manneorama May 01 '11 at 11:03
  • Please don't put status updates like [UPDATE] or [SOLVED] in your question titles - a clear summary of the question is all that's needed. Don't worry, everyone can see when you've updated your question. – razlebe May 11 '11 at 11:14

3 Answers3

1

Seeing as you are not changing where the pointer is pointing, you only need to pass in a char * to your function. So

int Crawl :: splitUrl(char *tmp, int max_length, char *url)
ColWhi
  • 1,077
  • 6
  • 16
0
for (i=0;i<maxUrlSize || p[i] != '\0';i++)
    tmp[idx][i] = p[i];

This for loop can't be correct. You copy bytes a long as either condition is true. I believe you should copy only when both are true.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
-1

Yes, this is correct. Every Parameter in C works as call by value, if you need a modification (fill your array), you should use a pointer.

       int Crawl :: splitUrl(char ***tmp, int max_length, char *url)
        {
         int idx=0;
         char * p;
         int i;

         p = strtok (url,"/");
         while (p != NULL)
          {

           for (i=0;i<maxUrlSize || p[i] != '\0';i++)
            (*tmp)[idx][i] = p[i];
           for ( ; i< maxUrlSize-1;i++)
            (*tmp)[idx][i] = '\0';

           printf("tmp[idx] %s\n",(*tmp)[idx]);

           idx++;
           p = strtok (NULL, "/");
          }


         return idx;
        };

...
      arr_size = crawl->splitUrl(&split_url,maxUrlSplits,url);
user411313
  • 3,930
  • 19
  • 16