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 access Std
), however you must move the new[]
statement into main()
after Num
has been read in, eg:
#include <iostream>
#include <string>
using namespace std;
struct s1 {
string str1;
};
s1* Std;
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
Std = new s1[Num];
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd[" << i << "].str1 : " << Std[i].str1 << "\n\n";
}
delete[] Std;
}
That being said, you should use the standard std::vector
container instead whenever you need a dynamic array, eg:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct s1 {
string str1;
};
vector<s1> Std;
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
Std.resize(Num);
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd[" << i << "].str1 : " << Std[i].str1 << "\n\n";
}
}