Do I get NULL from STRTOK?

Asked

Viewed 172 times

1

Hello, I am using Strtok to split a string into words. My idea was to follow the word REMOVE deleted the next word from the text.

void algorithm(node **root, char *line){
    char *pch = strtok(line, " ");
    while(pch != NULL){
        if(strcmp(pch, "REMOVE")==0){
            pch = strtok(NULL, " ");
            if(pch == NULL){
                printf("error?");
            }
            removeNode(&(*root),pch);
        }else{
            insert(&(*root), pch);
        }
        pch = strtok(NULL, " ");
    }
}

Why is it after pch = strtok(NULL, " "); always have pch = NULL ?

Note: I already tested with large files and a REMOVE in the middle and the pch after this operation always gives NULL, if the operation is at the end of the variable cycle pch no longer stays NULL.

  • In this case you should not use strncmp(pch, "REMOVE", 6) and not a simple strcmp?

  • The problem is not in the comparison, it is in the pch call = Strtok(NULL, ""). I will explain when I read a "REMOVE", go to the following word with the pch = Strtok(NULL, ") command and have it removed. The problem is here when I try to access the next word the value returned to pch is NULL.

  • But you’re not just comparing the 6 characters of the string pointed by pch to "REMOVE", you’re comparing the entire string that starts in pch to "REMOVE". It will only be the same if "REMOVE" is the end of the string.

  • I did the test with strncmp(pch, "REMOVE", 6) and the error remains the same, because the problem is not in the comparison but in the assignment of pch that always gives null.

  • Sorry, I got confused with the commands. You are right to use strcmp.

  • Checks whether the function removeNode() alters the pch?

  • &(*apontador) is the same as apontador :)

Show 2 more comments

1 answer

0


I gave up the strtok() and I’m reading the words one by one is much more efficient and I don’t spend so much memory space.

while(scanf("%s ", word) > 0){
            if(removeNext){
                removeNode(&root, word);    
                removeNext = 0;
            }
            else if(strcmp(word, "REMOVE") != 0){
                i = 0;
                while(i < sizeof(word)){
                    word[i] = tolower(word[i]);
                    i++;
                }
                insert(&root, word);    
            }
            else if(strcmp(word, "REMOVE")==0){
                removeNext = 1;
            }
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.