This answer is based on an edited question and various comments / observations in other answers ...
First, what are the possible states for pStart when calling Next ()?
- pStart - NULL (default constructor or otherwise set to NULL)
- * pStart is '\ 0' (empty line at the end of the line)
- * pStart - delim (empty string in the adjacent delimiter)
- * pStart is something else (a token is not an empty string)
At this point, we only need to worry about the first option. Therefore, I would use the original "if" here:
if (pStart == NULL) { return NULL; }
Why don't we need to worry about cases 2 or 3? You probably want to treat adjacent delimiters as having a token with an empty string between them, including at the beginning and end of the line. (If not, tune in.) The while loop will handle this for us if you also add the "\ 0" check (necessary independently):
while (*pStart != delim && *pStart != '\0')
After a while loop, you have to be careful. What are the possible conditions now?
- * pStart is '\ 0' (end of token at end of line)
- * pStart - delim (end of token on the next delimiter)
Note that pStart cannot be NULL here.
You need to return pNextWord (current token) for both of these conditions so that you do not discard the last token (i.e. when * pStart is '\ 0'). The code correctly processes register 2, but not case 1 (the source code dangerously increases by pStart for "\ 0", the new code returns NULL). In addition, it is important that reset pStart for case 1 is correct, so the next call to Next () returns NULL. I will leave the exact code as an exercise for the reader, as this is homework in the end;)
This is a good exercise to describe the possible data states in the entire function, in order to determine the correct action for each state, similar to the formal definition of basic cases compared to recursive cases for recursive functions.
Finally, I noticed that you delete calls to both pStart and pNextWord in your destructor. First, to remove arrays, you need to use delete [] ptr; (i.e. remove the array). Secondly, you will not delete both pStart and pNextWord, because pNextWord points to the pStart array. Thirdly, pStart no longer points to the beginning of memory, so you need a separate element to store the initial launch to call delete [] . Finally, these arrays are allocated on the stack, not on the heap (i.e., using char var[] , not char* var = new char[] ), and therefore they should not be deleted. Therefore, you should simply use an empty destructor.
Another good tip is to count the number of calls new and delete ; should be the same amount of each. In this case, you have zero new calls and two delete calls, which indicates a serious problem. If it were the other way around, it would mean a memory leak.