C ++将值传递给函数中的2D char数组

时间:2015-04-22 20:05:51

标签: c++ arrays function sorting lvalue

我正在尝试使用函数对一个充满单词的char数组进行排序。我当前遇到的问题是,在我的sortNames函数中,我收到错误,“表达式必须是可修改的左值”,在下面的部分

hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;

我猜它是因为我试图通过数组传递值由于某种原因。我正在努力理解引用和指针等等,我想这也伤害了我。任何帮助都会很棒,谢谢你提前。

这是我目前的代码......

#include <iostream>
#include <string>

using namespace std;

char nameArr[20][15];           // array to store the 20 values
int val = 0;                    // variable to pass values to the array
int x = 0;                      // loop counter outside functions

//Function prototypes
void getNames(char (&nameArr)[20][15], int &val);
void sortNames( char(&nameArr)[20][15]);

//getNames Function
void getNames(char (&nameArr)[20][15], int &val)
{
    int i = 0;                  // loop counter

    cout << "Awesome, now lets input those names...\n" << endl; 

    for (i = 0; i < val; i++)
    {
        cout << "\nNAME " << i+1 << ": " << ' ';
        cin >> nameArr[i];
    }

    cout << "\n\n\nThese are the names that you inserted:\n" << endl;

    for (i = 0; i < val; i++)
    {
         cout << nameArr[i] << "\n" << endl;
    }
}

// sortNames function
void sortNames( char(&nameArr)[20][15])
{
    int n = 15;             // max length of word
    int ii = 0;             // loop counter
    int jj = 0;             // other counter
    string hold;            // holding array

    for (int ii = 0 ; ii < n ; ii++) 
    {   
         for (int jj = ii + 1; jj < n; jj++) 
        {
             if (nameArr[ii] > nameArr[jj])
            {
                hold = nameArr[ii];
                nameArr[ii] = nameArr[jj];
                nameArr[jj] = hold;
            }
        }
    }
}


int main()
{
    cout << "NAME SORTER!\n\nPlease enter in the amount of names you wish to enter: " << ' ';
    cin >> val;

    getNames(nameArr, val);

    cout << "\n\n\nAlright, lets sort now..." << endl;

    sortNames(nameArr);

    cout << "\nHere are the results:\n" << endl;

    for (x = 0; x < val; x++)
    {
         cout << nameArr[x] << "\n" << endl;
    }

    system("pause");
 }

2 个答案:

答案 0 :(得分:3)

这里的主要问题是你试图在两个固定大小的数组上使用赋值运算符,这是不合法的。请考虑以下代码:

int a[2] = {0, 0};
int b[2] = {1, 1};

a = b;

这会给您带来同样的错误。在你提到的那些行上,你对char[15]数组做了同样的事情。

要解决您的问题,您需要动态分配char数组/使用指针,或者更简单的解决方案是将char[][]数组更改为string[]阵列。

话虽这么说,你可以在这里清理很多东西:

  • 您有一些全局声明的变量,可以在main或更低的
  • 中定义
  • 您可以在for循环内声明循环计数器,而不是事先声明,就像在sortNames函数
  • 中那样
  • sortNames中,您要声明两个变量

答案 1 :(得分:0)

我会在dwcanilla的回答中添加一些内容。

您需要将函数原型和标题更改为更像这样的内容:

void getNames(char ** & arr, int val);
void sortNames(char ** & arr);

这意味着该函数接受对c字符串数组的引用;也就是说,当您在函数中使用数组时,您正在修改传递的实际数组而不仅仅是副本。另外我认为你可以通过getNames的值传递整数。

其次,全局变量通常是一个坏主意。由于您可以将数组引用直接传递给函数,因此您可能希望在main中声明nameArr和其他全局变量。

第三,在getNames中,您将无法使用cin直接分配您的c字符串。

编辑:这是一个更好的方法 - getting console input for Cstrings

最后,&lt;运算符不能像在排序函数中使用它那样处理c字符串。请改用strcmp()(并确保包含cstring标头):

if(strcmp(arr[ii], arr[jj]) > 0)