2013-05-17 123 views
1

我寫了一個小程序,我無法將二維數組words[10][max_row_size]傳遞給函數notify。如果可以,請你幫助我。
附帶代碼的一部分。
如何將二維數組傳遞到函數

#include <iostream> 
#include <cstdlib> 
#include <fstream> 
#include <string.h> 
#include <unistd.h> 
using namespace std; 
#define max_row_size 100 
int notify(char words[max_row_size]); 

int main(void) { 
    ifstream dictionary("dictionary.txt"); 
    //ditrionary looks like 
    //hello-world 
    //universe-infinity 
    //filename-clock 
    string s; 
    int i=0; 
    char words[10][max_row_size]; 
    while(!dictionary.eof()){ 
     dictionary>>s; 
     strcpy(words[i++],s.c_str()); 
    } 
     notify(words[max_row_size]); 

    return 0; 
} 

int notify(char words[max_row_size]){ 
     cout<<words[1]; 
    return 0; 
} 

It is a full code of my programm, may be it can help you

這是一個錯誤
/home/rem/projects/github/notify_words/notify_words.cpp: В функции «int notify(int, char*)»:
/home/rem/projects/github/notify_words/notify_words.cpp:65:113: предупреждение: format «%s» expects argument of type «char*», but argument 3 has type «int» [-Wformat]

+0

一般情況下,它總是好發佈你的代碼產生的錯誤。這樣可以更容易地提供幫助。 – Simon

+0

這裏是一個全面的答案:http://stackoverflow.com/a/8767247/1837457 –

+0

編譯結果 - 行 –

回答

0

你通過它自己的話說:char** words是函數的參數:即

int notify(char** words){... 
0

我猜你要通知打印只有一個字,所以您需要更改通知

int notify(char* word){ 
    cout<<word; 
    return 0; 
} 

而且你打電話通知可能不會產生你之後的結果的方式。

notify(words[max_row_size]); 

會試圖讓你成爲第10個100字,這可能會導致崩潰。

你可能要放置通知最後在while循環,並調用它

notify(words[i]); 

另外,如果你在你的字典超過10個字,你就麻煩了。您可能想嘗試vector而不是數組(因爲矢量可以動態增長)。

+0

yes,crash '不能轉換«char *»到«char **»的參數«1»到«int notify(char **)»' –

+0

二維數組不是指針的指針,所以這個函數不會工作 – spiritwolfform

+0

不,但是當傳遞給函數時可以像對待他們一樣對待他們。當然,你必須改變呼叫通知(單詞)。我仔細看了一下代碼,並試圖建議一些代碼,這些代碼完成了我認爲OP實際上試圖實現的目標。 – Simon

0

2維數組(很明顯,你可以的typedef的數組)最簡單的方法:

int notify(std::array<std::array<char, max_row_size>, 10>& words){ 
    std::cout << words[1]; 
    return 0; 
} 

最簡單的字符串數組:

int notify(std::array<std::array<std::string>, 10>& words){ 
    std::cout << words[1]; 
    return 0; 
} 

這樣可以防止該陣列衰減到函數中的一個指針,所以尺寸仍然是已知的。

0
notify(char words[][max_row_size]) 

通過整個數組後

然後使用notify(words);調用方法

不過說真的,你應該使用標準集裝箱,而不是陣列