簡體   English   中英

字符數組上的printf問題

[英]Issue with printf on char array

下面的代碼利用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"

免費從哪里來?

問題是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�

甚至無法打印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM