c++/动态分配
创建*std
作为全局变量。
创建*std
作为多个num
输入时。
由于num
包含在main()
中,因此未执行此代码。
从main(Main()
获取num
输入时,是否有一种方法可以将*std
设置为全局变量?
#include <iostream>
#include <string>
using namespace std;
struct s1 {
string str1;
};
s1* Std = new s1[Num];
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd["<<i<<"].str1 : " << Std[i].str1<<"\n\n";
}
}
Create *Std
as a global variable.
Create *Std
as many Num
as you enter.
This code is not executed because Num
is contained within main()
.
Is there a way to set *Std
as a global variable while getting Num
input from main()
?
#include <iostream>
#include <string>
using namespace std;
struct s1 {
string str1;
};
s1* Std = new s1[Num];
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd["<<i<<"].str1 : " << Std[i].str1<<"\n\n";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在声明时不必初始化变量。您可以将声明与分配分开。
在这种情况下,您可以将
std
作为一个全局变量,如果您真的想(尽管, Globals通常是在上皱眉,在这种情况下,这是不必要的main()
在num
已读取,例如:说,您应该使用标准
std :: vector
当您需要动态数组时,容器,例如:Variables don't have to be initialized at the time they are declared. You can separate declaration from assignment.
In this case, you can leave
Std
as a global variable, if you really want to (though, globals are generally frowned upon, and in this case it is unnecessary since there are no other functions wanting to accessStd
), however you must move thenew[]
statement intomain()
afterNum
has been read in, eg:That being said, you should use the standard
std::vector
container instead whenever you need a dynamic array, eg: