【问题标题】:C++ Structs and Dynamically Allocated ArraysC++ 结构和动态分配的数组
【发布时间】:2026-01-20 10:55:02
【问题描述】:

这是我目前所拥有的。当我尝试向数组添加项目时,程序崩溃。我正在寻找它来最终存储项目,以及获取当前时间,并将项目标记为未完成,直到用户输入“完成”。

不能使用 - 标准容器或智能指针

#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;

struct List{
    string items;
    char completed;
    int time_t;

};

int main()
{
    // Declare Variables
    int userChoice = 0;
    int numItems = 0;
    int count = 0;
    List* list = new List[];

    // Get current time
    time_t recordedTime = time(nullptr);
    tm localTime = *localtime(&recordedTime);

    // Give the user some options
    cout << "1. Add Item" << endl;
    cout << "2. Remove Item" << endl;
    cout << "3. Sort Items" << endl;
    cout << "4. Mark as Completed" << endl;
    cout << "5. Exit" << endl;
    cout << "Enter the number of the operation you wish to perform: ";
    cin >> userChoice;
    cout << endl;

    // Perform the operation
    switch(userChoice)
    {
    case 1:
        {
            cin.ignore(50, '\n');
            cout << "Enter one item per line, or enter 'done' to finish\n";

        while(true)
        {
            do{
                count++;
                cout << "Item" << count << ": ";
                getline(cin, list[count].items);
            }
            while(list[count].items !="done");

            if(list[count].items == "done")
            {
                break;
            }
          }
        }
        break;
    case 2:
        {

        }
        break;
    case 3:
        {

        }
        break;
    case 4:
        {
            cout << "Item #: ";
        }
        break;
    case 5:
        {
            return 0;
        }

    }

    // Output the list
    cout << "-------Items-------" << endl;

    cout << "Enter the number of the operation you wish to perform: ";
    cin >> userChoice;


    return 0;
}

【问题讨论】:

  • 您的代码中没有数组。
  • 您正在对指向单个结构的指针使用下标间接。
  • 您能否详细说明您的代码“不起作用”的原因?你期待什么,实际发生了什么? 如果您遇到异常或错误,请发布它发生的行和详细信息。edit这些详细信息,否则我们可能无法提供帮助。
  • 我得到的错误是在第 24 行的 的调试中
  • List* list = new List[]; 格式不正确(一些 cmets 建议分配 1 大小的列表,但事实并非如此)

标签: c++ arrays struct


【解决方案1】:

我的建议是您应该使用vector 来包含您的所有项目。但这会大大改变你的代码。

更简单的方法是将您的列表定义更改为 List* list = new List[1000]; 这将分配一个大小为 1000 的数组,您之前的定义只分配一个 List,并使用指针 list 指向它。

编辑

如果您不知道大小,您应该使用vector 将您的列表定义为vector&lt;List&gt; list,并使用push_back 将项目附加到容器。

喜欢

{
    cout << "Item" << count << ": ";
    string str;
    getline(cin, str);
    List item {str, 'N', localtime};
    list.push_back(move(item));
} 

编辑

不能使用stl,只有内存限制,我认为你必须将你的List定义更改为LinkedList,比如

struct List{
    string items;
    char completed;
    int time_t;
    List* next;
};

并且每次输入时分配内存,你必须有另一个指针来记住你输入的最后一项。 如果你不使用 stl,你将很难排序。

【讨论】:

  • 问题是我需要数组来保存无限数量的项目(仅受内存限制)。
  • 我没有提到对于这个特定的项目,我们不能使用像 std::vector 这样的任何标准容器
  • @bradym55 您需要根据需要不时调整阵列大小
最近更新 更多