C++ 使用函数调整动态结构数组的大小

C++ 使用函数调整动态结构数组的大小,c++,struct,dynamic-arrays,C++,Struct,Dynamic Arrays,从我所读到的内容来看,我应该不会对我的代码有任何问题。 我正在阅读Alex Allain跳进C++中,他复制了这样的动态int数组,但是当我尝试以同样的方式复制一个结构数组时,它给了我这个错误: Unhandled exception at 0x777108B2 in Friend Tracker.exe: Microsoft C++ exception: std::length_error at memory location 0x006FF838. 根据我的理解,这告诉我堆数据用完了。但是

从我所读到的内容来看,我应该不会对我的代码有任何问题。 我正在阅读Alex Allain跳进C++中,他复制了这样的动态int数组,但是当我尝试以同样的方式复制一个结构数组时,它给了我这个错误:

Unhandled exception at 0x777108B2 in Friend Tracker.exe: Microsoft C++ exception: std::length_error at memory location 0x006FF838.
根据我的理解,这告诉我堆数据用完了。但是我有14GB未使用的RAM,这怎么可能呢

当看到其他人有同样错误的问题时,他们正在保存多个1GB大小的阵列副本

这让我觉得问题出在内存中的位置,但是为什么编译器没有在我的新数组中分配正确数量的堆数据呢

struct frnd
{
    string firstName;
    string lastName;
    int lastTalked;
};

int main()
{
    int size = 1;
    frnd* friendsList;

    friendsList = new frnd[2];
    friendsList[1].firstName = "larry";
    frnd* temp;
    temp = new frnd[4];

    for (int i = 1; i < 3; i++)
    {
        temp[i] = friendsList[i];
    }

    delete[] friendsList;

    friendsList = new frnd[4];
    for (int i = 1; i < size; i++)
    {
        friendsList[i] = temp[i];
    }

    delete[] temp;

    cout << "\n\n" << friendsList[1].firstName << "\n\n";
    system("PAUSE");
    return 0;
}
struct frnd
{
字符串名;
字符串lastName;
最后一次谈话;
};
int main()
{
int size=1;
frnd*友人名单;
friendsList=新朋友[2];
friendsList[1]。firstName=“larry”;
frnd*温度;
温度=新frnd[4];
对于(int i=1;i<3;i++)
{
temp[i]=朋友列表[i];
}
删除[]好友列表;
friendsList=新朋友[4];
对于(int i=1;ic> 您的错误是由于C++中的数组索引为零,但您使用数组索引的方式与数组类似。
for (int i = 1; i < 3; i++) {
    temp[i] = friendsList[i];
}

关于代码的其他想法:

  • 我知道这段代码是一个练习。但是,对于生产代码,我需要建议使用
  • 使用命名空间std;

我强烈建议不要复制未初始化的数据。无论是<代码> ListTalk < /Cuth>成员都在复制其值时初始化,并且没有为第二个复制循环初始化。跳入Alex Allain的C++中。如果您所写的是书中的代码示例,它会使任何人“跳出C++”。在C++中数组索引从零开始。因此,即使你得到了正确的维度,你的循环也会从数组的末尾掉下来。更糟糕的是,你的代码在代码中比它的代码> FristsList</代码>中的元素多。顺便说一下,问题不是书的错。你没有正确地阅读这本书,更多地依赖猜测。只是好奇,我能用STD::copy代替for循环吗?还有,我在哪里使用向量?
struct frnd
{
    frnd() : lastTalked(0) { }

    string firstName;
    string lastName;
    int lastTalked;
};