我需要有关正确创建函数的帮助,然后将其传递给函数。 我有一段这样的代码:
struct phones {
char lastname[15];
char number[8];
char city[15];
} *list;
void enter(phones[], int);
int main()
{
int n;
cout << "Enter the number of users: ";
cin >> n;
list = new phones[n];
enter(list, n);
system("pause");
delete[]list;
return 0;
}
void enter(phones list[], int n) {
for (int i = 0; i < n; i++)
{
cout << "User number " << i + 1 << endl;
cout << "Enter user's lastname ";
cin >> list[i].lastname;
cout << "Enter user's number: ";
cin >> list[i].number;
cout << "Enter user's city: ";
cin >> list[i].city;
}
}
我的老师告诉我,直接使用 *list
创建结构是不好的。
现在我有一个问题,如何正确创建结构,根据用户输入声明一个大小,然后将其传递给函数。
最佳答案
你总是可以在声明一个struct
之后定义变量:
phones *list;
C++ 没有 VLA,因此要么使用动态分配,根据您的描述这是不允许的,要么使用 C++ 中的特殊内容:STL。
创建一个struct phones
的 vector 可以使它变得非常简单:
#include <vector>
// After input number
std::vector<phones> list(n);
而且您不必为新建
和删除
而烦恼。
关于c++ - 创建结构并传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006410/