2014-09-12 58 views
1

錯誤發生在行:錯誤打印的數組用C

printf("\n%s was found at word number(s): %d\n", search_for, pos); 

我想打印我的整數(pos)的數組,但我不知道怎麼做。我通過命令行運行它,我得到這個錯誤:

search_word.c:57:28: warning: format specifies type 'int' but the argument hastype 'int *' [-Wformat] search_for, pos); 

代碼:

const int MAX_STRING_LEN = 100; 

void Usage(char prog_name[]); 

int main(int argc, char* argv[]) { 
    char search_for[MAX_STRING_LEN]; 
    char current_word[MAX_STRING_LEN]; 
    int scanf_rv; 
    int loc = 0; 
    int pos[MAX_STRING_LEN] = {0}; 
    int word_count = 0; 
    int freq = 0; 

    /* Check that the user-specified word is on the command line */ 
    if (argc != 2) Usage(argv[0]); 
    strcpy(search_for, argv[1]); 

    printf("Enter the text to be searched\n"); 
    scanf_rv = scanf("%s", current_word); 
    while (scanf_rv != EOF && strcmp(current_word, search_for) != MAX_STRING_LEN) { 
     if (strcmp(current_word, search_for) == 0) { 
      loc++; 
      freq++; 
      pos[loc] = word_count; 
     } 
     word_count++; 
     scanf_rv = scanf("%s", current_word); 
    } 
    if (freq == 0) 
     printf("\n%s was not found in the %d words of input\n", 
       search_for, word_count); 
    else 
     printf("\n%s was found at word number(s): %d\n", 
       search_for, pos); 
    printf("The frequency of the word was: %d\n", freq); 

    return 0; 
} /* main */ 

/* If user-specified word isn't on the command line, 
* print a message and quit 
*/ 
void Usage(char prog_name[]) { 
    fprintf(stderr, "usage: %s <string to search for>\n", 
      prog_name); 
    exit(0); 
} /* Usage */ 
+0

就像編譯器告訴你的那樣,pos是一個指向int的指針,而不是int。這是一個完整的陣列。你想打印哪一個? – 5gon12eder 2014-09-12 21:06:51

+0

我想打印已存儲的整個整數數組 – 2014-09-12 21:07:53

+0

然後您需要使用循環。 – Barmar 2014-09-12 21:08:14

回答

1

pos是一個數組。您必須在循環中打印它。

不要

else { 
    printf("\n%s was found at word number(s): ", 
      search_for); 
    for (int index = 0; index < MAX_STRING_LEN; index++) 
      printf("%d ", pos[index]); 

    printf("\n"); 
} 
+0

如果不是'pos'中的所有'MAX_STRING_LEN'插槽都被使用了? – 2014-09-12 21:10:37

+0

在問題OP表示它想要打印整個陣列。 – Arpit 2014-09-12 21:12:49

1

你需要循環在陣列上。 C沒有任何辦法在一個單獨的語句來打印int秒的數組:

else { 
    int i; 

    printf("\n%s was found at word number(s): ", search_for); 

    for (i = 0; i < loc; ++i) { 
    if (i > 0) 
     printf(", "); 
    printf("%d", pos[i]); 
    } 

    printf("\n"); 
} 

在此之前,雖然,確保你在正確的時間增加loc。按原樣,您將第一個元素留空。

if (strcmp(current_word, search_for) == 0) { 
    pos[loc] = word_count; 
    loc++; 
    freq++; 
} 
+0

太棒了。這工作。我只是不知道必須遍歷一個數組才能打印。現在我明白了。 – 2014-09-12 21:28:51