【发布时间】:2015-03-10 00:08:58
【问题描述】:
下面的代码是利用 strtok 方法,将 strtok 得到的单词存储到 char * 数组单词中。然后我试图以相反的顺序打印 char * 数组单词中的单词。我得到一个额外的词,我不知道它来自哪里。有什么帮助吗?
代码:
#include <stdio.h>
#include <string.h>
/* What characters are used to separate words? */
#define DELIMITERS " "
#define MAX_SIZE 100
int main() {
/* A simple string for illustration */
char line[] = "seven years ago our fathers brought forth";
/* A pointer to be used by strtok() */
char *ptr;
char *words[MAX_SIZE];
printf("Before processing: \"%s\"\n", line);
/* Find the first word in the line */
ptr = strtok(line, DELIMITERS);
int i = 0;
while (ptr != NULL) {
/* process the current word */
/*printf("\"%s\"\n", ptr);*/
words[i] = ptr;
/* get the next word in the line */
ptr = strtok(NULL, DELIMITERS); /* NB: line is NOT the first argument! */
i++;
}
/* Observe that strtok() modifies the string we have been scanning */
printf("After processing: \"%s\"\n", line);
int j;
puts("Outputting words in reverse order : ");
/* print out strings in reverse order */
for (j = (sizeof(&words) - 1); j >= 0; j--) {
printf("\"%s\"\n", words[j]);
}
return 0;
}
输出:
./a.out
Before processing: "seven years ago our fathers brought forth"
After processing: "seven"
Outputting words in reverse order :
"free"
"forth"
"brought"
"fathers"
"our"
"ago"
"years"
"seven"
免费从哪里来??
【问题讨论】: