【问题标题】:Dynamic array of structures (Not allowed to use <std::vector>)结构的动态数组(不允许使用 <std::vector>)
【发布时间】:2021-01-07 21:17:30
【问题描述】:

对于我的编程项目基础,我必须编写一个小应用程序,允许用户学习波兰语和英语的单词和短语。我项目的第一个函数将 100 个波兰语和英语单词加载到标准结构数组中。然后,对于负责我的应用程序的两种模式之一的功能(第一种是免费学习,另一种是测验),我想创建一个较小的动态结构数组,该数组将具有与用户输入一样多的元素,例如,如果您输入 10,此函数将创建一个 10 元素的动态结构数组。然后它会要求您翻译给定的单词/短语,直到您给出正确的答案。我被困在如何创建结构的动态数组上。由于某些难以想象的原因,我不允许使用非标准库(禁止使用 std::vector 和 std::array)。到目前为止,这是我的代码

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];


}

这些方法中哪一种是正确的? :

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

【问题讨论】:

  • 如果你想要Wyrazenie的动态数组,那么第二种方法是正确的。第一种方法给出了一个指向(动态分配的)Wyrazenie 的静态指针数组。
  • @Beta 谢谢,函数最后我只需要写delete Wyrazenie[] 对吧?
  • 是的,没错。

标签: c++ struct dynamic


【解决方案1】:

在 C++ 中以传统方式创建动态分配的结构数组的正确答案如下所示:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2015-09-19
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多