0

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";
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
김선유
  • 3
  • 3
  • It's better to move `s1* Std = new s1[Num];` to after `cin >>Num;` and avoid using global variables. – drescherjm Apr 20 '22 at 00:39
  • @drescherjm I know that if I do, the code works. But I think it would be more convenient to set [*Std] as a global variable. – 김선유 Apr 20 '22 at 00:54
  • 1
    change `s1* Std = new s1[Num];` to `s1* Std{};` then put `Std = new s1[Num];` after `cin >>Num;` – drescherjm Apr 20 '22 at 00:56
  • @drescherjm It was helpful. Thank you! – 김선유 Apr 20 '22 at 01:02
  • I suggest to use a global variable at least one for your coding lifetime. Because the lesson learned when it is backfired is pretty meaningful.. At least I don't want to use it anymore. – Louis Go Apr 20 '22 at 01:35

1 Answers1

0

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";
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770