سؤال

Im trying to create a function that tokenizes a given string with given delimeters, puts the tokens in a 2D char array and returns it. Below the code is displayed:

char** stringTokenizer(const char* str, const char* delims){
       char** tokens;
       size_t len = strlen(str);
       char localstr[len+1];
       int tokenslen=0;
       strcpy(localstr, str);
       tokens=malloc(sizeof(char*));

       char* tmp = strtok(localstr, delims);
       while(tmp){
                  if(++tokenslen>1) realloc(tokens, tokenslen*sizeof(char*));
                  tokens[tokenslen-1]=malloc((strlen(tmp)+1)*sizeof(char));
                  strcpy(tokens[tokenslen-1],tmp);
                  tmp = strtok(NULL, delims);
       }
       if(tokenslen==0){
                        free(tokens);
                        return NULL;

       } else return tokens;
}

When i try printing any of tokens[i] im getting a crash.

As long there is a token I increment the size of the tokens array and allocate the pointer for the token to be copied.

Any suggestions?

Thanks!

هل كانت مفيدة؟

المحلول

Try doing this

char** stringTokenizer(const char* str, const char* delims){
       char** tokens = NULL;
       size_t len = strlen(str);
       char localstr[len+1];
       int tokenslen=0;
    char **temp;//Change
       strcpy(localstr, str);

       //tokens=malloc(sizeof(char*));

       char* tmp = strtok(localstr, delims);
       while(tmp){
                  //if(++tokenslen>1) realloc(tokens, tokenslen*sizeof(char*));
    temp = realloc(tokens, tokenslen*sizeof(char*));
    tokens = temp;
                  tokens[tokenslen-1]=malloc((strlen(tmp)+1)*sizeof(char));
                  strcpy(tokens[tokenslen-1],tmp);
                  tmp = strtok(NULL, delims);
       }
       /*if(tokenslen==0){
                        free(tokens);
                        return NULL;

       } else*/ return tokens;
}

Thank you @netcoder

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top