char数组上的printf问题

时间:2015-03-10 00:08:59

标签: c printf strtok

下面的代码正在使用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"

免费来自哪里?

1 个答案:

答案 0 :(得分:2)

问题是sizeof(&words) - 1是错误的,因为sizeof(&words)是指针的大小,sizeof(void *)在你的平台上似乎是8所以你的for循环是那么

for (j = 7 ; j >= 0; j--) 

因为数组中的第八个位置没有任何内容可以打印垃圾值,所以将for循环更改为

for (j = i  - 1 ; j >= 0; j--) 

至于为什么它打印free非常不可预测,在你的情况下,它可能来自二进制文件中的调试符号,但是当读取未经初始化的数据时,结果在我的情况下是不可预测的印刷值是

���A�

甚至不可打印。