0

For my basics of programming project I have to write a small app that allows the user to learn words and phrases in polish and english. The first function of my project loads 100 polish and english words into a standard array of structures. Then, for the function responsible for one of two modes of my app(first is free-learning and the other is quiz) I want to create a smaller, dynamic array of structures that will have as many elements as the user inputs, eg if you input 10, this function will create a 10-element dynamic array of structures. Then it asks you for translations of given words/phrases until you give a correct answer. I'm stuck on how to creat the dynamic array of structures.For some unimaginable reason im not allowed to use non-standard libraries(std::vector and std::array are forbidden). Here is my code so far

void WczytywanieWyrazen(Wyrazenie Polskie[100], Wyrazenie Angielskie[100])
{
    int i = 0, j = 0;
    fstream plik1("PolskieSlowka.txt", ios::in);
    fstream plik2("AngielskieSlowka.txt", ios::in);

    string Fraza;
    string Phrase;

    for (int i = 0; i < 100; i++)
    {
        Polskie[i].wartosc = 0;
        Angielskie[i].wartosc = 0;
    }

    while (getline(plik1, Fraza))
    {
        Polskie[i].zwrot = Fraza;
        i++;
    }

    while (getline(plik2, Phrase))
    {
        Angielskie[j].zwrot = Phrase;
        j++;
    }

    plik1.close();
    plik2.close();
}

void TrybNauki()
{
    srand(time(NULL));
    int m;
    cout << "Please enter how many words would you like to practice (1-100): ";
    cin >> m;


    Wyrazenie* Fiszki = new Wyrazenie[m];


}

Which one of those methods is correct? :

    Wyrazenie* Fiszki[m];
    for (int i = 0; i < 100; i++)
    {
        Fiszki[i] = new Wyrazenie;
    }
    /////////////////////
    Wyrazenie* Fiszki = new Wyrazenie[m];

1 Answers1

0

The correct answer to create a dynamically assigned array of structs the traditional way in C++ looks like this:

struct Structure{
int x;
int y;
};
//...
cin >> m;

Structure* MyStruct[m] = new Structure; // creates an array of pointers type struct
for(int i = 0; i < SomeValue; ++i)
MyStruct[i].x = Value;

//or you could make a structure like that

for(int i = 0; i < SomeValue; ++i){
Structure _Var;
_Var.x = Value;
_Var.y = Some other value;
Mystruct[i] = _Var;
}

//Never forget to free up the memory!
delete[] MyStruct;

//Now, if for some reason you need to have a 2D array created dynamically the //"traditional" way, it would look something like this

Structure** MyStruct = new Structure* [m];// Creates an array of pointers to arrays of pointers

for(int i = 0; i<SomeValue ++i)
MyStruct[i] = new Structure;

//Now freeing up the memory looks something like this

for(int i = 0; i<SomeValue ++i){
delete MyStruct[i];
MyStruct[i] = NULL;
}

delete[] MyStruct;
MyStruct = NULL;