2013-05-17 83 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);调用方法

不过说真的,你应该使用标准集装箱,而不是阵列