传递和更新结构阵列

Passing and updating a structural array

本文关键字:结构 阵列 更新      更新时间:2023-10-16

所以我的程序遇到了一些麻烦。它似乎无法正确填充阵列。即使我在增加i,它似乎并没有填充通行元素0。当我调试回去时,我仍然保持零。我应该做一些不同的事情吗?我觉得我正在通过或更新阵列不当。真的无法使用任何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;

}

因此,我添加了 1以返回客户端,然后设置i = clientcount。但是,clientCount保持零且未更新。

数组之后不具有任何值的原因是因为您从未达到第一个元素。您可以在功能末尾增加i,但是在addClnt功能的顶部,i设置为0。这只会继续覆盖旧的先前数据

编辑:

#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";
}

clientCount仅在该函数范围中增加。当该功能转到其返回语句时,所有变量及其所做的所有工作都完全消失了。

您是按值传递的,而不是通过引用传递,因此客户端将始终为0,并将其递增该本地函数实际上不会更改函数的外部。

您需要做的是通过参考将其传递。

编辑:所选的答案不能解释他的解决方案为什么有效。提供的答案不正确。

该代码工作的原因是,您再次通过参考而不是通过值传递。