传递和更新结构阵列
Passing and updating a structural array
所以我的程序遇到了一些麻烦。它似乎无法正确填充阵列。即使我在增加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,并将其递增该本地函数实际上不会更改函数的外部。
您需要做的是通过参考将其传递。
编辑:所选的答案不能解释他的解决方案为什么有效。提供的答案不正确。
该代码工作的原因是,您再次通过参考而不是通过值传递。
相关文章:
- 如何将来自文本文件的数据读取到结构的int阵列中
- 将数据从阵列火阵列传输到犰狳结构
- 将阵列的元素变为结构
- c/c qsort在结构内的结构阵列
- 生态2D结构阵列C
- 如何计算结构阵列内的平均值
- 工会结构阵列的初始化太多
- 如何在C 中创建动态分配的2D结构阵列
- 动态分配的结构阵列具有动态分配的结构阵列元素
- 传递和更新结构阵列
- C 98如何在标题中初始化静态结构阵列
- C 结构阵列带指针
- 用null C 初始化结构阵列
- 结构阵列奇数/偶数故障
- 排序二维结构阵列
- 如何确定另一个结构内的结构阵列的长度
- 结构阵列的初始化列表的行为
- 在结构阵列(AoS)和阵列结构(SoA)之间来回切换
- 2D结构阵列
- 用于将结构阵列(AoS)转换为阵列结构(SoA)的干净代码