Home > Enterprise >  C / Dynamic Assignment
C / Dynamic Assignment

Time:04-20

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";
    }
}

CodePudding user response:

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";
    }
}
  • Related