[英]C++ array of char pass to functions
嘿伙計們,我需要幫助。 我正在寫一個真正的基本程序,它將生成一個字符數組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
}
我知道這是錯誤的,請原諒我。 我讓它工作到只有錯誤的地步,但后來我決定更改所有內容。 無論如何,我希望你能理解我要說的話。 基本上我需要傳遞數組並在函數內部對其進行修改。 我怎么可能這樣做?
謝謝!
編輯:好的,所以我也不能使用全局變量,這太容易了。
我編輯了代碼以擺脫&。 它給了我
錯誤LNK2019:無法解析的外部符號“ void __cdecl deletePerson(int&,int,char(* const)[25],char(* const)[25],char(* const)[50],char(* const)[16 ])函數_main中引用的“(deletePerson @@ YAXAAHHQAY0BJ @D1QAY0DC @ DQAY0BA @ D @ Z”)
我的新代碼看起來像
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)
{
}
}
我認為你應該真的避免使用char數組和char指針。 使用std::vector
和std::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)
{
}
}
嘗試這個:
它使用模板參數推導和引用來簡化事物。 它適用於您在不更改函數(可能還有邏輯)的情況下因任何原因更改數組的尺寸。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.