char 数组上的 printf 问题

Issue with printf on char array

下面的代码是利用strtok方法,将strtok得到的单词存储到char *数组words中。然后我试图以相反的顺序打印 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"

自由从何而来??

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

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

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

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

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

���A�

甚至无法打印。