使用C ++中的指针将2维数组传递给函数

时间:2013-06-10 15:04:31

标签: c++

我一直试图将这个数组传递给函数,但我继续得到,  错误C2664:'correctans':无法将参数2从'std :: string [3] [3]'转换为'std :: string **',不要介意愚蠢的问题。编码它只是随机进行测试。

代码:

    #include <iostream>
    #include <string>
    using namespace std;

int correctans(string *arr1, string **arr2, int *arr3, int questions, int choices)
{
int count=0;
int ans;

    for(int i=0; i<questions; i++)
    {
        cout << "Question #" << i+1;
      cout << arr1[i] << endl;
      for(int j=0; j<choices; j++)
          cout << j+1 << arr2[i][j] << " ";
      cout << "your answer:";
      cin >> ans;
      if(ans==arr3[i])
          count++;
    }

    return count;
}

int main()
{
    int correct;
    string Questions[3]={"HowAreYou", "HowManyHandsDoYouHave", "AreYouCrazyOrCrazy"};
    string Choices[3][3]={{"Banana", "Peanut", "Fine"},{"Five", "Two", "One"},{"I'mCrazy", "I'mCrazyBanana", "I'mDoubleCrazy"}};
    int Answers[3]={3, 2, 3};

    correct=correctans(Questions, Choices, Answers, 3, 3);
    cout << "You have " << correct << " correct answers" <<endl;

    return 0;
}

4 个答案:

答案 0 :(得分:1)

你去吧

int correctans(string * arr1,string(&amp; arr2)[3] [3],int * arr3,int questions,int choices)`

答案 1 :(得分:1)

传递多维数组可能会非常混乱。我建议创建一个指向数组开头的单指针,然后传递指针:

    #include <iostream>
    #include <string>
    using namespace std;

int correctans(string *arr1, string *arr2, int *arr3, int questions, int choices)
{
int count=0;
int ans;

    for(int i=0; i<questions; i++)
    {
        cout << "Question #" << i+1;
      cout << arr1[i] << endl;
      for(int j=0; j<choices; j++)
          cout << j+1 << arr2[i][j] << " ";
      cout << "your answer:";
      cin >> ans;
      if(ans==arr3[i])
          count++;
    }

    return count;
}

int main()
{
    int correct;
    string Questions[3]={"HowAreYou", "HowManyHandsDoYouHave", "AreYouCrazyOrCrazy"};
    string Choices[3][3]={{"Banana", "Peanut", "Fine"},{"Five", "Two", "One"},{"I'mCrazy", "I'mCrazyBanana", "I'mDoubleCrazy"}};
    int Answers[3]={3, 2, 3};

    string* choicesPtr=&Choices[0][0];
    correct=correctans(Questions, choicesPtr, Answers, 3, 3);
    cout << "You have " << correct << " correct answers" <<endl;

    return 0;
}

此代码编译并执行。

答案 2 :(得分:0)

如果我没记错的话,可以使用&#39; string [] []&amp; RARRAY&#39;
(或者确切地说:string [3] [3]&amp; rArray),当然你也应该将实际尺寸作为参数传递。

编制者接受了这个:
    string arr2 [3] [3]
作为参数。但我会尝试改进传递指针而不是按值复制数组。既然你正在使用stl :: string,你也可以尝试vector&lt;矢量&lt;字符串&gt; &GT;

答案 3 :(得分:0)

好吧,因为编译器说std::string [3][3]无法转换为std::string **

你可以试试这个

int correctans(string *arr1, string (* arr2)[ 3 ], int *arr3, int questions, int choices)

或者

int correctans(string *arr1, string arr2[][ 3 ], int *arr3, int questions, int choices)

但更好的解决方案是使用std::vector