C++ 传递和更新结构数组

C++ 传递和更新结构数组,c++,arrays,struct,reference,C++,Arrays,Struct,Reference,所以我的程序有点问题。它似乎没有正确填充数组。它似乎没有填充pass元素0,即使我增加了I。当我调试并返回时,我仍然是零。我应该做些不同的事情吗?我觉得我不正确地传递或更新了数组。无法真正使用任何STL库。提前感谢您的帮助 struct Client { string name; string zip; double balance; }; Client bAccounts [30]; //structural array in main() int addClnt(Client(&

所以我的程序有点问题。它似乎没有正确填充数组。它似乎没有填充pass元素0,即使我增加了I。当我调试并返回时,我仍然是零。我应该做些不同的事情吗?我觉得我不正确地传递或更新了数组。无法真正使用任何STL库。提前感谢您的帮助

struct Client
{
string name;
string zip;
double balance;
};

Client bAccounts [30]; //structural array in main()

int addClnt(Client(&bAccounts)[30], int); //prototype
int addClnt(Client(&bAccounts)[30], int clientCount) //function to add 
elements

{

cout << "Enter Account Name:" << endl;
cin >> bAccounts[i].name;

cout << "Enter Account Zip:" << endl;
cin >> bAccounts[i].zip;

cout << "Enter Account Balance:" << endl;
cin >> bAccounts[i].balance;


cout << "Enter Last Transaction" << endl;
cin >> bAccounts[i].lastTrans;

clientCount++; //to return number of clients added
i++; //to populate different element of array on next call of function.

return clientCount + 1;
struct客户端
{
字符串名;
拉链;
双平衡;
};
客户数量[30]//main()中的结构数组
int addClnt(客户和银行账户)[30],int)//原型
int addClnt(Client(&bAccounts)[30],int clientCount)//要添加的函数
元素
{
cout bAccounts[i].名称;
cout-bAccounts[i].zip;
cout-bAccounts[i].平衡;
cout-bAccounts[i].lastTrans;
clientCount++;//返回添加的客户端数
i++;//在下次调用函数时填充数组的不同元素。
返回clientCount+1;
}


所以我添加了+1以返回clientCount,然后设置I=clientCount。但是,clientCount保持为零且不更新。

数组在第一个元素之后没有任何值的原因是,您从未到达第一个元素。在函数末尾增加
i
,但在
addClnt
函数的顶部,
i
被设置回
0
。这只会导致覆盖以前的旧数据

编辑:

#包括
//使用按引用传递(&)
无效添加客户端(内部和索引位置){
//做任何事
//这将更改传递到函数中的实际值
索引_loc++;
}
int main(){
int loc=0;
添加_客户(loc);
添加_客户(loc);
添加_客户(loc);
//产出3

std::coutclientCount只在该函数范围内递增。当该函数转到它的return语句时,所有变量和它所做的所有工作都已完全停止

您是按值而不是按引用传递clientCount,因此clientCount将始终为0,并且在该局部函数内增加它实际上不会在函数外更改clientCount的值

您需要做的是通过引用传递它

编辑:所选答案无法解释其解决方案工作的原因。提供的答案不正确


代码之所以能够工作,也是因为您是通过引用而不是通过值来传递的。

您可以使用调试器逐步检查代码,查看各种变量,看看哪里出了问题。如果没有帮助,请编辑您的问题以包括(格式正确)a.谢谢你的提示,Phil。我删除了一些不需要的代码。啊,好吧,这很有意义。我是否需要保留它的值,还是需要某种循环?我只想请求一次数据,然后退出函数。你可以传递你想要添加有意义的值的索引位置。所以我添加了+1以返回clientCount a然后设置i=clientCount。但是,clientCount仍然为零,并且不会更新。非常感谢,你真的帮助了我。我真诚地感谢你的帮助。我没有思考,错过了显而易见的解决方案。
#include <iostream>

//use pass by reference (&)
void add_client(int& index_loc){

    //do whatever

    //this changes the actual value passed into the function 
    index_loc++;

}

int main(){

    int loc = 0;

    add_client(loc);
    add_client(loc);
    add_client(loc);

    //outputs 3 
    std::cout << "current #: " <<  loc << "\n";

}