我下面的代码中似乎发生了一些奇怪的事情。当 nthtoken() 中的任何 printf 被注释时,main() 中不会显示任何标记,但是当取消注释 nthtoken() 中的任何 printf 时,main() 中会显示标记。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *nthtoken (char *origStr, char *delimiters, int nth);
int main (void) {
char *str = "in principio creavit deus caelum et terram";
char *delims = " ";
char *tok = nthtoken (str, delims, 3);
printf ("token: %s\n", tok);
return (EXIT_SUCCESS);
}
char *nthtoken (char *origStr, char *delimiters, int nth) {
char str[strlen (origStr)];
strncpy (str, origStr, strlen (origStr) + 1);
char *token = NULL;
token = strtok (str, delimiters);
// printf ("first token: %s\n", token);
int i = 0;
for (i = 0; i < nth; i++) {
token = strtok (NULL, delimiters);
//printf ("token inside the loop: %s\n", token);
}
// printf ("token before returning to main(): %s\n", token);
return token;
}