shyam wrote:
> Hi All
>
> Here is a program which basically tokenizes a string based on space
> seperation.
> But it does not run bcoz i am directly trying to manuplate the string.
> I cannot use standard string functions due to performance issues
>
> can anybody figure out whats gone wrong with this
>
>
>
> #include<stdio.h>
> #include<string.h>
> #include<malloc.h>
Non-standard header. malloc() is declared in:
#include <stdlib.h>
>
>
> #define SP ' '
>
>
> char **tokenize(char *);
>
>
> char ** tokenize(char *ch)// to tokenize the string based on space
> {
>
>
> int count = 0;
> char *mrk = ch;
>
>
> while(*ch != '\0')
> {
> if(*ch == SP)
>
>
> count++;
>
>
> ch++;
>
>
> }
>
>
> count = count + 2;
>
>
> ch = mrk;
>
>
> char **c = (char **)malloc(count * sizeof(ch));
There's no need to cast the return value of malloc(), doing so can mask
errors. Better:
char **c = malloc(count * sizeof *c);
>
>
> int count2;
> char *fst,*lst;
>
>
> fst = lst = ch;
>
>
> for (count2 = 0; count2 < count - 1; count2++)
> {
>
>
> lst = strchr(lst,SP);
>
>
> *lst = '\0'; //the DDD crashes at this point
Right. `lst' points somewhere into the array of chars passed to the
function. In this case (see main() below) it is a string literal which
is not guaranteed to be modifiable.
>
>
> lst++;
>
>
> c[count2] = fst;
>
>
> fst = lst;
> }
>
>
> c[count - 1] = NULL;
>
>
> return c;
>
>
>
> }
>
>
> int main()
> {
>
> char *s = "hello how do u do"
Try:
char s[] = "hello how do u do";
[BTW, you had a missing semicolon above. Cut and paste *real* code in
the future.]
;
>
>
> char **t = tokenize(s);
>
>
> printf("the str is %s\n",*t[0]);//similarly for s[1] & s[2]
>
>
>
> }
>
Next time:
1) Post *real* code.
2) Get rid of all those absolutely useless blank lines.
Also, be aware that there may be (and most likely are) further bugs in
your code; there's just no way I'm going to go through it with a fine
toothed comb when presented like this.
HTH,
--ag
--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com (new post 8/5)
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"