我在动态分配结构时遇到问题

I'm having trouble dynamically allocating my struct

本文关键字:遇到 问题 结构 动态分配      更新时间:2023-10-16

我创建了一个简单的程序来帮助我了解如何动态分配结构。我希望程序从用户那里获得5个名称和5个帐户,并显示这些名称和帐户。我知道指针就像一个引用变量,唯一的区别不是传递值,而是传递变量的地址。我为第23行("getline(std::cin,clientPtr[count].name);")、第25行("std::cin.ignore(std:;numeric_limits:max(),'\n');",第27行("std::cin>>clientPtr[count].accounts;")、第40行("td::cout<<名称:"<<clientPtr[count].Name;")、第41行("std::cout<<名称:"<<clientPtr[count]].Name;")和第31行(showInfo(&client);)。当我调试时,它显示第41行没有执行。它应该显示每个客户端的名称和帐户。在这种情况下,情况并非如此。我不知道为什么,只是我的一点背景知识,我是C++的新手,也是使用调试器的新手。我使用的是xcode 8.2,我使用的调试器是lldb。我是来学习的,所以任何事情都会有所帮助。谢谢

#include <iostream>
#include <limits>
struct BankInfo
{
std::string name;
std::string accounts;
};
void showInfo(BankInfo*);
int main()
{
BankInfo client;
BankInfo* clientPtr=nullptr;
clientPtr = new BankInfo[5];
for(int count =0; count < 5; count++)
{
std::cout << "Enter your name:";
getline(std::cin,clientPtr[count].name);
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'n');
std::cout << "Enter you account number:";
std::cin >>clientPtr[count].accounts;

}
showInfo(&client);

return 0;
}
void showInfo(BankInfo* clientPtr)
{
for(int count =5; count < 5; count++)
{
std::cout <<"Name:" << clientPtr[count].name;
std::cout <<"Account:" << clientPtr[count].accounts;
}
}

你把错误的东西交给了showInfo()。你有两个变量。。单个BankInfo变量和大小为5的动态分配数组。

您希望对后者进行迭代,而不是对前者进行迭代。

showInfo(&client);更改为showInfo(clientPtr);也许可以做到这一点?

所以我修复了我犯了几个错误的解决方案,但感谢您的建议。以下是我所做的。

#include <iostream>
#include <limits>
struct BankInfo
{
std::string name;
std::string accounts;
};
void showInfo(BankInfo*);
int main()
{
BankInfo client;
BankInfo* clientPtr=nullptr;
clientPtr = new BankInfo[5]; //Allocate an array of BankInfo struct on the heap
for(int count =0; count < 5; count++)
{
std::cout << "Enter your name:";
getline(std::cin,clientPtr[count].name); // stores the value in the name member
std::cout << "Enter you account number:";
std::cin >>clientPtr[count].accounts; // stores the value in accounts member
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'n');
}
showInfo(clientPtr);
delete [] clientPtr;
clientPtr = nullptr;
return 0;
}
void showInfo(BankInfo* clientPtr)
{
for(int count =0; count < 5; count++)
{
std::cout <<"nName:" << clientPtr[count].name; // dereference the pointer to the structure 
std::cout <<"nAccount:" << clientPtr[count].accounts; // dereference the pointer to the structure
}
}
for(int count=1 ; count<=5 ; count++)
{
//do your stuff here
}