【问题标题】:Issue with printf on char arraychar数组上的printf问题
【发布时间】: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"

免费从哪里来??

【问题讨论】:

    标签: c printf strtok


    【解决方案1】:

    问题在于sizeof(&amp;words) - 1 是错误的,因为sizeof(&amp;words) 是指针的大小,即sizeof(void *),在您的平台上似乎是8,所以您的for 循环就是

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

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

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

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

    ���A�
    

    甚至无法打印。

    【讨论】:

    • 是的,但是“免费”从何而来?
    • @NathanTuggy 我假设它来自调试符号,因为您正在访问未初始化的数据。
    • 这似乎很合理,但最好能对特定症状有一个可靠、详细的解释。
    • 我想知道下一个词是不是“啤酒”,这样我们就可以开派对了。 :)
    • 我该如何解决这个问题?如果我只使用单词而不使用 &words,则会出现分段错误。
    猜你喜欢
    • 2022-01-22
    • 2011-11-24
    • 1970-01-01
    • 2018-07-30
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多