C ++数组的char传递给函数

时间:2010-11-29 06:46:25

标签: c++ arrays function

嘿伙计们,我需要帮助。我正在编写一个非常基本的程序,它将生成一个字符数组firstName [amount] [size]。使用它,然后将它传递给函数addPerson,这将修改值。

这是我当前的代码

void deletePerson(int &, int, char[], char[], char[], char[]);
int main()
{
char firstNames[100][25], lastNames[100][25], email[100][50], phone[100][16];
else if (userChoice == 'D')
    {
        deletePerson(count, amount, &firstNames,&lastNames,&email,&phone);
    }
}
void deletePerson(int count, int amount, firstNames&, lastNames&,email&,phone&);
{
//blahblahblah
}

我知道这是错的并原谅我的新手。我让它工作到只有错误但我决定改变一切的地步。无论如何,我希望你明白我想说的话。基本上我需要传递数组并在函数内部进行修改。我怎么可能这样做?

谢谢!

编辑:好的,所以我也不能使用全局变量,这太容易了。

我编辑了代码以摆脱&amp ;. 它给了我

错误LNK2019:未解析的外部符号“void __cdecl deletePerson(int&,int,char(* const)[25],char(* const)[25],char(* const)[50],char(* const)[16])“(deletePerson @@ YAXAAHHQAY0BJ @D1QAY0DC @ DQAY0BA @ D @ Z)在函数_main

中引用

我的新代码看起来像

void deletePerson(int &, int, char[][25], char[][25], char[][50], char[][16]);
int main()
{
char firstNames[100][25], lastNames[100][25], email[100][50], phone[100][16];
else if (userChoice == 'D')
        {
            deletePerson(count, amount, firstNames,lastNames,email,phone);
        }
}
void deletePerson(int count, int amount, char firstNames[100][25], char lastNames[100][25],char email[100][50],char phone[100][16])
{
    int position; //the place where the person is in the array
    position = searchName(count, amount, lastNames);
    if (position != -1)
    {
    }

}

2 个答案:

答案 0 :(得分:2)

我认为你应该真的避免使用char数组和char指针。请改用std::vectorstd::string,这样可以省去很多麻烦。 std::vector<std::string>可能就是你所需要的。或者甚至更好,你应该将firstName,lastName,email和phone捆绑在一起。

struct Person
{
    std::string firstName;
    std::string lastName;
    std::string email;
    std::string phone;
}

void deletePerson(std::vector<Person>& persons)
{
    int position = searchName(lastNames); // you could replace this with std::find
    if (position != -1)
    {
    }
}

答案 1 :(得分:0)

试试这个:

它使用模板参数推导和引用来简化事物。它适用于您在不更改函数(可能还有逻辑)的情况下因任何原因更改数组的尺寸。

template<class T, int N1, int N2, int N3, int N4, int N5, int N6, int N7, int N8>
void deletePerson(int &, int, T(&r1)[N1][N2], T(&r2)[N3][N4], T(&r3)[N5][N6], T(&r4)[N7][N8]){} 

int main() 
{ 
   char firstNames[100][25], lastNames[100][25], email[100][50], phone[100][16]; 
   int count = 100;
   deletePerson(count, 20, firstNames, lastNames, email, phone); 
}